SpringMVC以及SpringBoot整合SpringDataJPA简单入门

 

1.Spring Data JPA的概述

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第1张图片

Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!

Spring Data JPA 让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作工程中,推荐使用Spring Data JPA + ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使数据库层操作更加简单,方便解耦

1.2.Spring Data JPA 与 JPA和hibernate之间的关系

JPA是一套规范,内部是有接口和抽象类组成的。hibernate是一套成熟的ORM框架,而且Hibernate实现了JPA规范,所以也可以称hibernate为JPA的一种实现方式,我们使用JPA的API编程,意味着站在更高的角度上看待问题(面向接口编程)

Spring Data JPA是Spring提供的一套对JPA操作更加高级的封装,是在JPA规范下的专门用来进行数据持久化的解决方案。

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第2张图片

 

2.Spring Data JPA的快速入门

2.1搭建Spring Data JPA的开发环境

MVC依赖:



    4.0.0

    springdatajpa_test
    springdatajpa_test_02
    1.0-SNAPSHOT

    
        5.0.7.RELEASE
        5.0.7.Final
        2.0.1.RELEASE
        1.6.6
        3.2.0
        5.1.6
        4.12
    

    
        
        
            junit
            junit
            ${junit.version}
            test
        
        
            org.springframework
            spring-test
            ${spring.version}
        
        
        
            org.springframework
            spring-context
            ${spring.version}
        

        
            org.springframework
            spring-aspects
            ${spring.version}
        

        
            org.springframework
            spring-orm
            ${spring.version}
        

        
        
            org.hibernate
            hibernate-core
            ${hibernate.version}
        

        
            org.hibernate
            hibernate-entitymanager
            ${hibernate.version}
        

        
            com.zaxxer
            HikariCP
            ${hikari.version}
        

        
        
            org.slf4j
            slf4j-log4j12
            ${slf4j.version}
        

        
            mysql
            mysql-connector-java
            ${mysql.version}
        

        
            org.springframework.data
            spring-data-jpa
            ${springdatajpa.version}
        


        
        
            javax.el
            javax.el-api
            2.2.4
        

        
            org.glassfish.web
            javax.el
            2.2.4
        

    
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.1
                
                    1.8
                    1.8
                
            
        
    

 

Boot依赖:



    4.0.0

    test.springboot
    springdataJPA_test
    1.0-SNAPSHOT

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.2.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
        
            mysql
            mysql-connector-java
        

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
    

2.2整合Spring Data JPA与Spring

MVC:

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第3张图片

 




    
        
        
        
        
    
    
    
        
        
        
        
        
        
            
        
        
            
                
                
                
                
                
                
                
                
            
        
        
        
            
        
    
    
    
        
    
    
    

 

Boot:

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第4张图片

 

server:
  port: 80 #端口号
spring:
  datasource:  #数据库连接信息
    url: jdbc:mysql://localhost:3306/test_ssm_lvyou
    username: root
    password: 123
    #默认连接池
    hikari:
      max-lifetime: 28830000
      maximum-pool-size: 9
  redis:
    port: 6379
    host: 127.0.0.1
  #thymelea缓存
  thymeleaf:
    cache: false
  #springdataJPA
  jpa:
    database: mysql
    show-sql: true
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect

#日志级别
logging:
  level:
    org:
      springframework: info

 

3.使用JPA注解配置映射关系

@Entity  // 作用:指定当前类是实体类,代表要和某个表建立关系
@Table(name = "cst_customer") // 作用:指定实体类和表之间的对应关系。如果表名和当前类名一致,此注解可以省略
public class Customer implements Serializable {
    @Id
    @Column(name = "cust_id")//如果当前属性名和表的列名一致就可以省略
    @GeneratedValue(strategy = GenerationType.IDENTITY) //指定当前主键的生成策略
    /**
      IDENTITY 是mysql主键自增  
      EQUENCE 是oracle里的主键自增
     TABLE 是序列
     AUTO 是从IDENTITY TABLE SEQUENCE 根据数据库自动选择
     当是mysql时 序列  当是oracle时  SEQUENCE
    */
    private Long custId;
    @Column(name = "cust_name")
    private String custName;
    @Column(name = "cust_source")
    private String custSource;
    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_level")
    private String custLevel;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_phone")
    private String custPhone;

    public Long getCustId() {
        return custId;
    }

    public void setCustId(Long custId) {
        this.custId = custId;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustIndustry() {
        return custIndustry;
    }

    public void setCustIndustry(String custIndustry) {
        this.custIndustry = custIndustry;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustAddress() {
        return custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custSource='" + custSource + '\'' +
                ", custIndustry='" + custIndustry + '\'' +
                ", custLevel='" + custLevel + '\'' +
                ", custAddress='" + custAddress + '\'' +
                ", custPhone='" + custPhone + '\'' +
                '}';
    }
}

 

2.4 使用Spring Data JPA完成需求

2.4.1.编写符合Spring Data JPA规范的Dao层接口

Spring Data JPA是spring提供的一款对于数据访问层(Dao层)的框架,使用Spring Data JPA,只需要按照框架的规范提供dao接口,不需要实现类就可以完成数据库的增删改查、分页查询等方法的定义,极大的简化了我们的开发过程。

在Spring Data JPA中,对于定义符合规范的Dao层接口,我们只需要遵循以下几点就可以了:

1.创建一个Dao层接口,并实现JpaRepository和JpaSpecificationExecutor

2.提供相应的泛型

 

/**
 * The interface Customer dao.
 *
 * @auther 
 * @date 
 */
/*
 * JpaRepository<1.Customer,2.Long>
 *1.相关实体类 2.相关实体类的主键类型
 * 一般增删改查来自改接口
 *
 *JpaSpecificationExecutor<1.Customer>
 * 1.1.相关实体类
 * 高级查询来自改接口
 * */

public interface CustomerDao extends JpaRepository,JpaSpecificationExecutor {
    /**
     * Customer
     *
     * @return list
     */
    @Query("from Customer")
    List findAllCustomers();

    /**
     * Gets all by.
     *
     * @param custName the cust name
     * @return all by
     */
    @Query("from Customer where custName like ?1")
    List getAllBy(String custName);

    /**
     * Find custimer by name and id list.
     *
     * @param custName the cust name
     * @param id       the id
     * @return list
     */
    @Query("from Customer where custName like ?1 and custId=?2")
    List findCustimerByNameAndId(String custName,Long id);

    /**
     * JPQL默认都是查询操作,如果想要进行增删改就得加 @Modifying
     *
     * @param id        the id
     * @param custPhone the cust phone
     * @Modifying 代表是修改操作
     */
    @Query("update Customer set custPhone=?2 where custId=?1")
    @Modifying //代表是修改操作
    void updateCustomer(Long id,String custPhone);

    /**
     * 删除测试
     *
     * @param id the id
     */
    @Query("delete from Customer where custId=?1")
    @Modifying
    void deleteCustomer(Long id);

    /**
     * 方法命名规则查询
     *
     * @return the customer
     * @param custName
     */
     List findByCustName(String custName);

    /**
     *
     * @param custName
     * @param custPhone
     * @return
     */
    List findByCustNameIsLikeOrCustPhone(String custName,String custPhone);

    /**
     *  查询电话不为空并且ID为xxxx的用户
     * @param ids
     * @return
     */
    List findByCustIdInAndCustPhoneIsNotNull(Long [] ids);
}

2.4.2完成基本CRUD操作

完成了Spring Data JPA的环境搭建,并且编写了符合Spring Data JPA 规范的Dao层接口之后,就可以使用定义好的Dao层接口进行客户的基本CRUD操作。

 

/**
 *
 * 插入数据
 *
 */
 @Test
public void test1(){
     Customer customer = new Customer();
     customer.setCustName("你还好吗");
     customerDao.save(customer);
 }
/**
 * 查询数据
 */
@Test
public void test2() {
    //.orElse  设置从数据库查询回来的数据的默认值
    // 如果返回的数据有数据就显示返回数据   没有返回数据就显示默认值
    Customer customer = customerDao.findById(1l).orElse(null);
    System.out.println(customer);
}
/**
 * 修改数据
 */
@Test
@Transactional
@Rollback(false)//在单元测试上事务默认是自动事务回滚,所以要关闭测试事务回滚
public void test3() {
    Customer customer = customerDao.findById(2l).orElse(null);
    customer.setCustName("不好");
}
/**
 * 修改数据
 */
@Test
public void test4() {
    Customer customer = new Customer();
    customer.setCustId(3l);
    customer.setCustName("还好");

    customerDao.save(customer);
}
/**
 * 删除数据
 */
@Test
@Transactional //事务
@Rollback(false)
public void test5() {
    Customer customer = new Customer();
    customer.setCustId(1l);
    customerDao.delete(customer);
}

/**
 * 删除数据
 */
@Test
public void test6() {
    customerDao.deleteById(3l);
}
/**
 * 查询全部
 */
@Test
public void test7() {
    List customers = customerDao.findAll();
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

 

3.Spring Data JPA的内部原理剖析

3.1.Spring Data JPA的常用接口分析

在客户的案例中,我们发现在自定义的CustomerDao中,并没有提供任何方法就可以使用其中的很多方法,那么这些方法究竟是怎么来的呢?答案很简单,对于我们自定义的Dao接口,由于继承了JpaRepository和JpaSpecificationExecutor,所以我们可以使用这两个接口的所有方法。

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第5张图片

在使用Spring Data JPA时,一般继承JpaRepository和JpaSpecificationExecutor接口,这样就可以使用这些接口中定义的方法,但是这些方法都只是一些声明,没有具体的实现方式,那么在 Spring Data JPA中它又是怎么实现的呢?

 

3.2.Spring Data JPA的实现过程

通过对客户案例,以debug断点调试的方式,通过分析Spring Data JPA的原来来分析程序的执行过程

我们以findOne方法为例进行分析:

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第6张图片

断点执行到方法上时,我们可以发现注入的customerDao对象,本质上是一个代理对象。

代理对象中方法调用的分析:

当程序执行的时候,会调用JdkDynamicAopProxy的invoke方法。根据对Spring Data JPA介绍而知,要想进行findOne查询方法,最终还是会出现JPA规范的API完成操作,那么这些底层代码存在于何处呢?答案很简单,都隐藏在通过JdkDynamicAopProxy生成的动态代理对象当中,而这个动态代理对象就是SimpleJpaRepository。

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第7张图片

通过SimpleJpaRepository的源码分析,定位到了findOne方法,在此方法中,返回em.find()的返回结果,那么em又是什么呢?

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第8张图片

带着问题继续查找em对象,我们发现em就是EntityManager对象,而他是JPA原生的实现方式,所以我们得到结论Spring Data JPA只是对标准JPA操作进行了进一步封装,简化了Dao层代码的开发。

 

3.3.Spring Data JPA完整的调用过程分析

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第9张图片

 

 

4.Spring Data JPA的查询方式

4.1使用Spring Data JPA中接口定义的方法进行查询

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第10张图片

SpringMVC以及SpringBoot整合SpringDataJPA简单入门_第11张图片 
 

 4.1.1.findById和getOne的区别

/**
 * 查询
 * getOne 延迟加载
 */
@Test
@Transactional
@Rollback(false)
public void test1() {
    Customer customer = customerDao.getOne(1l);
    System.out.println(customer.toString());
}

说明:如果不在单元测试方法上@Transactional注解,则会报no session异常,原因是getOne方法执行完后,事务提交,session关闭;当打印customer对象时,需要通过session去查customer对象,可是session已经关闭,报no session异常。

findById和getOne的区别:

findById是立即加载,底层调用的是EntityManager中的find方法;
getOne是延迟加载,底层调用的是EntityManager中的getReference方法;

 

4.1.2 排序查询

/**
 * 排序查询
 *
 * Sort sort = new Sort(Sort.Direction.DESC,"custId",......);
 * 第一个参数:排序方式
 * 第二个参数:根据哪个属性名排序
 */
@Test
public void test2(){
    Sort sort = new Sort(Sort.Direction.DESC, "custId");
    List customers = customerDao.findAll(sort);
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}
/**
 * 排序多条件查询
 */
@Test
public void test3() {
   // Sort.Order custId = new Sort.Order(Sort.Direction.DESC, "custId");
    //Sort.Order custName = new Sort.Order(Sort.Direction.ASC, "custName");
    Sort.Order custId = Sort.Order.desc("custId");
    Sort.Order custName = Sort.Order.asc("custName");
    Sort sort = Sort.by(custId, custName);

    List customers = customerDao.findAll(sort);
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

4.1.3查询总记录数

/**
 * 查询总记录数
 */
@Test
public void test4() {
    long count = customerDao.count();
    System.out.println(count
    );
}

4.1.4检测某条记录是否存在existsById

/**
 * 检测某条记录是否存在
 */
@Test
public void test5() {
    boolean flag = customerDao.existsById(1l);
    System.out.println(flag);
}

 

4.2.使用JPQL的方式查询

使用Spring Data JPA提供的查询方法已经可以解决大部分的应用场景,但是对于某些业务来说,我们还需要灵活的构造查询条件,这时就可以使用@Query注解,结合JPQL的语句方式完成查询。

@Query 注解的使用非常简单,只需在方法上面标注该注解,同时提供一个JPQL查询语句即可。示例代码:

public interface CustomerDao extends JpaRepository,JpaSpecificationExecutor {    
    //@Query 使用jpql的方式查询。 
    @Query(value="from Customer") 
    public List findAllCustomer(); 
    //@Query 使用jpql的方式查询。?1代表参数的占位符,其中1对应方法中的参数索引 
    Query(value="from Customer where custName = ?1") 
    public Customer findCustomer(String custName);
}

此外,也可以通过使用 @Query 来执行一个更新操作,为此,我们需要在使用 @Query 的同时,用 @Modifying 来将该操作标识为修改查询,这样框架最终会生成一个更新的操作,而非查询。示例代码:

    @Query(value="update Customer set custName = ?1 where custId = ?2") 
    @Modifying 
    public void updateCustomer(String custName,Long custId);

4.2.1.查询所有

/**
 * Customer
 *
 * @return list
 */
@Query("from Customer")
List findAllCustomers();

 

/**
 * JPQL条件查询
 * 自定义查询
 * 主要是查询
 * 在dao层接口的自定义方法上加 @Query
 * 例子:@Query("from Customer where custName like ?1")
 * JPQL默认都是查询操作,如果想要进行增删改就得加 @Modifying
 */

/**
 * 查询所有
 */
@Test
public void test6() {
    List customers = customerDao.findAllCustomers();
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

4.2.2.条件查询

4.2.2.1 单一条件查询

/**
 * ?1:代表要把第一个参数custName给问号1
 * @param custName
 * @return
 */
@Query("from Customer where custName like ?1")
List getAllBy(String custName);
/**
 * 单一条件查询
 */
@Test
public void test7() {
    //String custName = "%马%";
    List customers = customerDao.getAllBy("%马%");
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

4.2.2.1 多条件查询

/**
 * 参数位置要和相应的问号位置对应
 * @param custName
 * @param id
 * @return
 */
@Query("from Customer where custName like ?1 and custId=?2")
List findCustimerByNameAndId(String custName,Long id);
/**
 * 多条件查询
 */
@Test
public void test8() {
    List customers = customerDao.findCustimerByNameAndId("%马%", 3l);
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

4.2.3.更新

/**
 * JPQL默认都是查询操作,如果想要进行增删改就得加 @Modifying
 *
 * @param id        the id
 * @param custPhone the cust phone
 * @Modifying 代表是修改操作
 */
@Query("update Customer set custPhone=?2 where custId=?1")
@Modifying //代表是修改操作
void updateCustomer(Long id,String custPhone);
/**
 * JPQL修改操作
 */
@Test
@Transactional
@Rollback(false)
public void test9() {
    customerDao.updateCustomer(3l, "123456789");
}

 

4.3.使用SQL语句查询

Spring Data JPA同样也支持sql语句的查询,如下:

         /**
          * nativeQuery : 使用本地sql的方式查询
          */
     @Query(value="select * from cst_customer",nativeQuery=true)
     public void findSql();

 

4.3.1.模糊查询

/**
     * 根据cust_name模糊查询
     * @param custName
     * @return
     */
@Query(value="select * from cst_customer where cust_name like ?1",nativeQuery = true)
 List findAllCustomerSql(String custName);

 

4.4.方法命名规则查询

顾名思义,方法命名规则查询就是根据方法的名字,就能创建查询。只需要按照Spring Data JPA提供的方法命名规则定义方法的名称,就可以完成查询工作。Spring Data JPA在程序执行的时候会根据方法名称进行解析,并自动生成查询语句进行查询。

按照Spring Data JPA 定义的规则,查询方法以findBy开头,涉及条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性首字母需大写。框架在进行方法名解析时,会先把方法名多余的前缀截取掉,然后对剩下部分进行解析。

示例代码:

//方法命名方式查询(根据客户名称查询客户)
public Customer findByCustName(String custName);

具体的关键字,使用方法和生产成SQL如下表所示

       
Keyword Sample JPQL    
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2    
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2    
Is,Equals findByFirstnameIs, findByFirstnameEquals … where x.firstname = ?1    
Between findByStartDateBetween … where x.startDate between ?1 and ?2    
LessThan findByAgeLessThan … where x.age < ?1    
LessThanEqual findByAgeLessThanEqual … where x.age <= ?1    
GreaterThan findByAgeGreaterThan … where x.age > ?1    
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1    
After findByStartDateAfter … where x.startDate > ?1    
Before findByStartDateBefore … where x.startDate < ?1    
IsNull findByAgeIsNull … where x.age is null    
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null    
Like findByFirstnameLike … where x.firstname like ?1    
NotLike findByFirstnameNotLike … where x.firstname not like ?1    
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)    
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)    
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)    
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc    
Not findByLastnameNot … where x.lastname <> ?1    
In findByAgeIn(Collection ages) … where x.age in ?1    
NotIn findByAgeNotIn(Collection age) … where x.age not in ?1    
TRUE findByActiveTrue() … where x.active = true    
FALSE findByActiveFalse() … where x.active = false    
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)    

 

4.4.1.等于查询

在CustomerDao中添加findByCustName方法,表示根据cust_name来查询,默认是等于查询:

/**
 * 方法命名规则查询
 *
 * @return the customer
 * @param custName
 */
 List findByCustName(String custName);
/**
 * 方法命名查询
 */
@Test
public void test11() {
    List customers = customerDao.findByCustName("马华腾");
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

4.4.2.like模糊查询

/**
 * 方法命名规则查询之模糊查询
 * 形参的顺序不能乱
 * @param custName
 * @param custPhone
 * @return
 */
List findByCustNameIsLikeOrCustPhone(String custName,String custPhone);
@Test
public void test12() {
    List customers = customerDao.findByCustNameIsLikeOrCustPhone("%jia%","1234567890");
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

4.4.3.多条件查询

在CustomerDao中添加findByCustNameLikeAndCustIndustry方法,相当于where cust_name like ? and cust_industry=?,形参的顺序不能乱。

/**
  * 方法命名规则查询,多条件查询
  * @param custName
  * @param custIndustry
  * @return
  */
List findByCustNameLikeAndCustIndustry(String custName,String custIndustry);

在CustomerDao中添加findByCustNameLikeAndCustIndustryIsNull方法,相当于where cust_name like ? and cust_industry is null

List findByCustNameLikeAndCustIndustryIsNull(String custName);

在CustomerDao中添加findByCustNameLikeOrCustIndustryIsNot方法,相当于where cust_name like ? or cust_industry != ?

List findByCustNameLikeOrCustIndustryNot(String custName,String custIndustry);

 

/**
 * 查询电话不为空并且ID为xxxx的用户
 * @param ids
 * @return
 */
List findByCustIdInAndCustPhoneIsNotNull(Long [] ids);
@Test
public void test13() {
    List customers = customerDao.findByCustIdInAndCustPhoneIsNotNull(new Long[]{1L, 2L, 3L});
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

 

5.Specifications动态查询

有时我们在查询某个实体的时候,给定的条件是不固定的,这时就需要动态构建相应的查询语句,在Spring Data JPA中可以通过JpaSpecificationExecutor接口查询。相比JPQL,其优势是类型安全,更加的面向对象。

/**
 * JpaSpecificationExecutor中定义的方法
 **/
public interface JpaSpecificationExecutor {
    //根据条件查询一个对象
    T findOne(Specification spec);
    //根据条件查询集合
    List findAll(Specification spec);
    //根据条件分页查询
    Page findAll(Specification spec, Pageable pageable);
    //排序查询查询
    List findAll(Specification spec, Sort sort);
    //统计查询
    long count(Specification spec);
}

对于JpaSpecificationExecutor,这个接口基本是围绕着Specification接口来定义的。我们可以简单的理解为,Specification构造的就是查询条件。

Specification接口中只定义了如下一个方法:

 //构造查询条件
/**
 * root   :Root接口,代表查询的根对象,可以通过root获取实体中的属性
 * query  :代表一个顶层查询对象,用来自定义查询
 * cb    :用来构建查询,此对象里有很多条件方法
 */
public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb);

 

5.1.使用Specifications完成单个条件查询

/**
 * Specifications动态查询
 */
@Test
public void test14() {

  Specification spec=new Specification() {
      /**
       * 生成条件
       * @param root  Root接口,代表查询的根对象,可以通过root获取实体中的属性
       * @param criteriaQuery   代表一个顶层查询对象,用来自定义查询(一般不用)
       * @param cb 用来构建查询,此对象里有很多条件方法
       * @return
       */
      @Override
      public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
         // 获取查询条件的属性  比如我要查询姓名,所以属性就是custName
          Path path = root.get("custName");
         // 构造条件
          Predicate predicate = cb.equal(path,"刘京东");

          return predicate;
      }
  };
    Customer customer = customerDao.findOne(spec).orElse(null);
    System.out.println(customer);
}

5.2.使用Specifications完成多个条件查询

/**
 * 多条件查询
 */
@Test
public void test15() {
    Specification spec=new Specification() {

        @Override
        public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
            //获取第一查询属性
            Path path1 = root.get("custName");
            //构造第一查询条件  注意:模糊查询要先指定数据类型
            Predicate predicate1 = cb.like(path1.as(String.class), "%马%");

            //获取第二查询属性
            Path path2 = root.get("custPhone");
            //获取第二查询条件
            Predicate predicate2 = cb.equal(path2, "0123456789");

            //因为只能返回一个predicate,所以要将两个综合一下  and 或是 or
            Predicate predicate = cb.or(predicate1, predicate2);
            /**
             * and的结果:
             * Customer{custId=2, custName='刘京东', custSource='null', custIndustry='null', custLevel='null', custAddress='null', custPhone='0123456789'}
             * or的结果:
             * Customer{custId=1, custName='马化腾', custSource='null', custIndustry='null', custLevel='null', custAddress='null', custPhone='0123456789'}
             * Customer{custId=2, custName='刘京东', custSource='null', custIndustry='null', custLevel='null', custAddress='null', custPhone='0123456789'}
             * Customer{custId=3, custName='刘京东', custSource='null', custIndustry='null', custLevel='null', custAddress='null', custPhone='1234567890'}
             */
            return predicate;
        }
    };
     //查询
    List customers = customerDao.findAll(spec);
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

 

5.3.使用Specifications完成多条件以及排序查询

/**
 * 多条件以及排序查询
 */
@Test
public void test16() {

    Specification spec=new Specification() {

        @Override
        public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
            //获取第一查询属性
            Path path1 = root.get("custName");
            //构造第一查询条件  注意:模糊查询要先指定数据类型
            Predicate predicate1 = cb.like(path1.as(String.class), "%马%");

            //获取第二查询属性
            Path path2 = root.get("custPhone");
            //获取第二查询条件
            Predicate predicate2 = cb.equal(path2, "0123456789");

            //因为只能返回一个predicate,所以要将两个综合一下  and 或是 or
            Predicate predicate = cb.or(predicate1, predicate2);

            return predicate;
        }
    };
    //条件以及排序查询
    Sort sort = new Sort(Sort.Direction.DESC,"custId");
    List customers = customerDao.findAll(spec,sort);
    for (Customer customer : customers) {
        System.out.println(customer);
    }
}

 

5.4分页查询

@Test
public void test17() {
    /**
     * 存储分页条件
     * @page 起始页数 从0开始
     * @size 每页记录数
     * @sort 排序
     */
    Sort sort = new Sort(Sort.Direction.DESC,"custId");
    PageRequest request = PageRequest.of(0, 2,sort);
    //返回的结果
    Page page = customerDao.findAll(request);

    System.out.println("总记录数:"+page.getTotalElements());
    System.out.println("总记页数:"+page.getTotalPages());
    //获取每页结果
    List customers = page.getContent();
    for (Customer customer : customers) {
        System.out.println("每页结果:"+customer);
    }

}

 

6.CriteriaBuilder cb 方法对应关系

方法名称 Sql对应关系
equle filed = value
gt(greaterThan ) filed > value
lt(lessThan ) filed < value
ge(greaterThanOrEqualTo ) filed >= value
le( lessThanOrEqualTo) filed <= value
notEqule filed != value
like filed like value
notLike filed not like value

 

 

你可能感兴趣的:(回顾,新技术)