SpringDataJpa01

无人久伴 提交于 2019-12-11 10:17:27

一、配置项标题目中pom.xml

主要作用:导包 和 设置版本

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.itsource</groupId>
  <artifactId>aisell</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>aisell Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <org.springframework.version>4.2.5.RELEASE</org.springframework.version>
    <org.hibernate.version>4.3.8.Final</org.hibernate.version>
    <spring-data-jpa.version>1.9.0.RELEASE</spring-data-jpa.version>
    <com.fasterxml.jackson.version>2.5.0</com.fasterxml.jackson.version>
    <org.slf4j.version>1.6.1</org.slf4j.version>
  </properties>
  <dependencies>
    <!-- Spring的支持包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- 上下文支持包(帮我们集成:模板,邮件,任务调度...) -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${org.springframework.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- 引入web前端的支持 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- SpringMCV上传需要用到io包-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!-- 文件上传用到的包 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- SpringMVC的json支持包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <!-- hibernate的支持包 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${org.hibernate.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${org.hibernate.version}</version>
    </dependency>
    <!-- SpringDataJpa的支持包 -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>${spring-data-jpa.version}</version>
    </dependency>
    <!-- SpringData的擴展包 -->
    <dependency>
      <groupId>com.github.wenhao</groupId>
      <artifactId>jpa-spec</artifactId>
      <version>3.1.1</version>
      <!-- 把所有的依賴都去掉 -->
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
    <!--lang3:工具包 java.lang.-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.5</version>
    </dependency>
    <!-- 測試包 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <!-- 这个scope 只能作用在编译和测试时,同时没有传递性。表示在运行的时候不添加此jar文件 -->
      <scope>provided</scope>
    </dependency>
    <!-- 日志文件 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${org.slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${org.slf4j.version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
    </dependency>
    <!-- 代码生成器模版技术  -->
    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity</artifactId>
      <version>1.6</version>
    </dependency>
    <!-- shiro(权限框架)的支持包 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-all</artifactId>
      <version>1.4.0</version>
      <type>pom</type>
    </dependency>
    <!-- shiro与Spring的集成包 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.4.0</version>
    </dependency>
    <!-- poi(操作办公软件)支持的jar包 -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.11</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.11</version>
    </dependency>
    <!-- 图片压缩功能 -->
    <!-- 缩略图 -->
    <dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.6</version>
    </dependency>
    <!-- 定时调度 -->
    <dependency>
      <groupId>quartz</groupId>
      <artifactId>quartz</artifactId>
      <version>1.5.2</version>
    </dependency>
    <!-- 邮件支持 -->
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.1</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>aisell</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>8.1.15.v20140411</version>
        <configuration>
          <stopPort>9966</stopPort>
          <stopKey>foo</stopKey>
          <webAppConfig>
            <contextPath>/</contextPath>
          </webAppConfig>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

二、集成SpringDataJpa

2.1配置jdbc.propeties

主要作用:连接数据库的配置文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssp
jdbc.username=root
jdbc.password=123456

2.2配置applicationContext.xml

主要配置:
开启扫描、读取jdbc.properties、配置连接池、开启事务注解支持

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <!--扫描service层的类-->
    <context:component-scan base-package="cn.itsource.aisell.service" />
    <!--
        db.properties -> dataSource(配置数据源[连接池dbcp]) -> EntityManagerFactory -> dao -> service
            -> 事务 -> controller(集成SpringMVC) -> easyui
    -->
    <!--1.读取db.properties, 注意:不要忘了加classpath-->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <!--2.配置dbcp连接池-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!--
        JPA:ORM规范  -> 很多框架实现了这个规范(hibernate,openjpa,toplink,...)
        3.配置EntityManagerFactory对象
            3.1 基本配置都是写在Spring中(四大金刚,建表策略,方言,是否显示SQL)
            3.2 Spring来创建这个对象(准备一个domain,如果运行的时候创建了表,就代表这个对象是成功的)
            alt+insert -> JPA -> LocalContainerEntityManagerFactoryBean
            ctrl+t/f4 : 有办法看结构
    -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--扫描JPA支持的注解-->
        <property name="packagesToScan" value="cn.itsource.aisell.domain" />
        <!--
            告诉Spring我们使用的是哪一个框架来完成JPA规范
            这里就需要我们配置一个适配器
            jpaVendorAdapter:JPA需要配置的适配器(我们会选择hibernate)
        -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--方言-->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                <!--
                    建表策略(已经有表有数据,不要删除了)
                -->
                <property name="generateDdl" value="false" />
                <!--是否显示sql-->
                <property name="showSql" value="true" />
            </bean>
        </property>
    </bean>
    <!--4.加上事务-->
    <!--4.1 准备事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <!--4.2 开启(注解)事务支持-->
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

三、集成SpringDataJpa

用来简化基于Spring构建的持久层框架的框架,使数据库访问变得方便快捷,减少代码量
用对象的角度操作数据库

3.1准备domain

3.1.1表对应的实体类

注意事项
在类上加上注解交给jpa管理
继承父类

@Entity
@Table(name = "表名")

3.1.2实体类的父类

父类的作用
方便扩展
公共的代码
制定规范
注意事项@MappedSuperclass
1.注解使用在父类上面,是用来标识父类的作用
2.标识的类表示其不能映射到数据库表,因为其不是一个完整的实体类,但是它所拥有的属性能够映射在 其子类对用的数据库表中
3.标识得类不能再有@Entity或@Table注解 但是可以使用@Id 和@Column注解

@MappedSuperclass
public class BaseDomain {
    @Id
    @GeneratedValue
    protected Long id;
}

3.2Repository(dao层)

注意事项
继承JpaRepository就可以使用其增删改查的普通方法

public interface EmployeeRepository extends JpaRepository<Employee,Long> {
    ...
}

扫描repository

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      ...
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      ...
      http://www.springframework.org/schema/data/jpa
      http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
">
   ...

    <!-- 让SpringDataJpa去扫描repository -->
    <jpa:repositories base-package="cn.itsource.aisell.repository"
                       <!-- 配置bean工厂-->
                      entity-manager-factory-ref="entityManagerFactory"
                      <!-- 配置事务-->
                      transaction-manager-ref="transactionManager" />

</beans>

四、CRUD功能

4.1增删改查

@Autowired
private EmployeeRepository employeeRepository;
查询所有
employeeRepository.findAll()
查询一条数据:
employeeRepository.findOne(1L)
添加/修改
employeeRepository.save(employee)
删除 
employeeRepository.delete(1L)

4.2 分页和排序

4.2.1 排序

注意事项
排序对象
第一个参数:排序的类型升序(ASC)还是降序(DESC)
第二个参数:排序的属性

Sort sort = new Sort(Sort.Direction.DESC,"属性");

List<Employee> list = employeeRepository.findAll(sort);
list.forEach(e-> System.out.println(e));

4.2.2 分页

注意事项
page:第几页(0就是第1页)
size:每页条数


Pageable pageable = new PageRequest(第几页,每页条数);
//在查询时,直接传入分页对象
Page<Employee> list = employeeRepository.findAll(pageable);
list.forEach(e-> System.out.println(e));

4.2.3 分页+排序

注意事项
直接在创建分页对象时,第三个参数传入排序对象

Sort sort = new Sort(Sort.Direction.DESC,"age");
Pageable pageable = new PageRequest(0,10,sort);
Page<Employee> list = employeeRepository.findAll(pageable);
list.forEach(e-> System.out.println(e));

4.3 根据条件进行查询

注意事项
根据文档中对应的命名规范写方法名

//根据用户名查询一个员工
Employee findByUsername(String username);

//用户名模糊查询
List<Employee> findByUsernameLike(String username);

//用户名与邮件模糊查询 
List<Employee> findByUsernameLikeAndEmailLike(String username,String email);

4.4 Query注解查询

Query注解可以自己写jpql或者sql进行查询

//根据用户名获取用户
@Query("select o from Employee o where o.username =?1")
Employee query01(String username);

//用户名与邮件模糊查询
@Query("select o from Employee o where o.username  like ?1 and o.email like ?2")
List<Employee> query02(String username,String email);
//    @Query("select o from Employee o where o.username  like :username and o.email like :email")
//    List<Employee> query02(@Param("username") String username,@Param("email")  String email);

//直接写原生的SQL
@Query(nativeQuery=true,value="select * from employee")
List<Employee> query03();

五.JpaSpecificationExecutor

注意事项
需要repository(dao)继承JpaSpecificationExecutor接口
gt/lt:大于/小于 ge/le:大于等于/小等等于

5.1 最简单的查询

     root:获取到实体对应的字段
     query: 组合条件(一般不用)
      cb :相当于条件或者条件组合
     Predicate:做成的一个查询语句
@Test
public void testJpaSpecificationExecutor01() throws Exception{
    List<Employee> list = employeeRepository.findAll(new Specification<Employee>() {
        @Override
        public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            //1.拿到Employee中的username字段
            Path usernamePath = root.get("username");
            //2.加上字段的判断关系
            Predicate p1 = cb.like(usernamePath, "%1%");
            return p1;
        }
    });

    list.forEach(e-> System.out.println(e));
}

5.2 多个条件查询

@Test
public void testJpaSpecificationExecutor02() throws Exception{
    //Specification:查询规则
    List<Employee> list = employeeRepository.findAll(new Specification<Employee>() {
        // root:拿到字段(表达式)  cb:设置条件(>,<,=,like),and/or
        @Override
        public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            //拿到属性并设置条件
            Path usernamePath = root.get("username");
            Predicate p1 = cb.like(usernamePath, "%1%");
            Path emailPath = root.get("email");
            Predicate p2 = cb.like(emailPath, "%2%");
            Path agePath = root.get("age");
            Predicate p3 = cb.gt(agePath, 18);
            //把条件结合起来
            return cb.and(p1, p2, p3);
        }
    });
    list.forEach(e-> System.out.println(e));
}

5.3 查询+分页+排序

//加上分页和排序功能
@Test
public void testJpaSpecificationExecutor04() throws Exception{
    //创建一个排序对象并添加到分页对象中 再添加到
    Sort sort = new Sort(Sort.Direction.DESC,"age");
    Pageable pageable = new PageRequest(0,10,sort);
    
    Page<Employee> page = employeeRepository.findAll(new Specification<Employee>() {
        @Override
        public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Path usernamePath = root.get("username");
            return cb.like(usernamePath, "%1%");
        }
    }, pageable);//传入规则执行者最后一个参数
    page.forEach(e->System.out.println(e));
}

六.jpa-spec

把JpaSpecificationExecutor变得更加简单的
文档说明: https://github.com/wenhao/jpa-spec/blob/master/docs/3.1.0_cn.md

6.1 简单查询

注意事项
导包 com.github.wenhao.jpa.Specifications;

//jpa-spec
//不要忘记最后的build();
@Test
public void testJpaSpec01() throws Exception{
    Specification<Employee> spec = Specifications.<Employee>and()
            .like("username", "%1%")
            .build();
    List<Employee> list = employeeRepository.findAll(spec);
    list.forEach(e-> System.out.println(e));
}

6.2 多条件查询

//jpa-spec
//完成咱们的简单查询 username like ? and email like ? and age>?
@Test
public void testJpaSpec02() throws Exception{
    Specification<Employee> spec = Specifications.<Employee>and()
            .like("username", "%1%")
            .like("email","%2%")
            .gt("age",18)
            .build();
    List<Employee> list = employeeRepository.findAll(spec);
    list.forEach(e-> System.out.println(e));
}

6.3 多条件+分页+排序

@Test
public void testJpaSpec03() throws Exception{
    //创建排序对象并传入分页对象中
    Sort sort = new Sort(Sort.Direction.DESC,"age");
    Pageable pageable = new PageRequest(0,10,sort);
    Specification<Employee> spec = Specifications.<Employee>and()
            .like("username", "%1%")
            .build();
    //功能执行时 传入规则和分页对象
    Page<Employee> page = employeeRepository.findAll(spec, pageable);
    page.forEach(e-> System.out.println(e));
}

七.Query抽取

7.1 BaseQuery

注意事项
抽取相同的分页对象
currrentPage 当前页数
pageSize 每页条数
orderType 排序的类型 true(DESC)/false(ASC)
orderName 排序的字段
让每个子类都有一个:createSpec()
解决传过来的是当前页从1开始(SpringDataJpa是从0开始计算)问题

public abstract class BaseQuery {
    private int currentPage=1;
    private int pageSize=10;
    private boolean orderType;
    private String orderName;

    //创建排序对象
    public Sort createSort(){
     //判断是否排序
        if(StringUtils.isNotBlank(orderName)){
            Sort sort = new Sort(orderType?Sort.Direction.DESC:Sort.Direction.ASC,orderName);
            return sort;
        }
        return null;
    }
 	//子类必须实现
    public abstract Specification createSpec();
    public int getJpaPage() {
    	//解决页数问题
        return currentPage-1;
    }
}

7.2 EmployeeQuery

子类的特殊字段查询

public class EmployeeQuery extends BaseQuery {

    private String username;
    private String email;
    private Integer age;

    //复写自己需要的查询规则
    @Override
    public Specification createSpec(){
        Specification<Employee> specification = Specifications.<Employee>and()
                .like(StringUtils.isNotBlank(username), "username", "%" + username + "%")
                .like(StringUtils.isNotBlank(email), "email", "%" + email + "%")
                .gt(age != null, "age", age)
                .build();
        return specification;
    }

}

7.3 测试


@Test
public void testJpaSpec04() throws Exception{
    //模仿前台传过来的数据
    EmployeeQuery query = new EmployeeQuery();
//        query.setUsername("1");
//        query.setEmail("2");
      query.setAge(18);
    query.setOrderName("age");
    query.setOrderType(true);

    //创建排序对象
    Sort sort = query.createSort();
    //创建分页对象(分页对象从前台传过来)
    Pageable pageable = new PageRequest(query.getJpaPage(),query.getPageSize(),sort);
    
    
	//规则对象(查询条件)
    Specification<Employee> spec = query.createSpec();
    //功能执行
    Page<Employee> page = employeeRepository.findAll(spec, pageable);
    page.forEach(e-> System.out.println(e));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!