SpringDataJpa复杂查询(3)

复杂查询常见用法
  • 借助接口中的定义好的方法完成查询
    findOne(id):根据id查询
    在继承JpaRepository,和JpaRepository接口后,就可以使用接口中定义的方法进行查询
  1. 继承JpaRepository后的方法列表
  2. 继承JpaSpecificationExecutor的方法列表
  • jpql的查询方式
    jpql : jpa query language (jpq查询语言)
    特点:
    语法或关键字和sql语句类似
    查询的是类和类中的属性
    需要将JPQL语句配置到接口方法上
  1. 特有的查询:需要在dao接口上配置方法
  2. 在新添加的方法上,使用注解的形式配置jpql查询语句
  3. 注解 : @Query
  • sql语句的查询
  1. 特有的查询:需要在dao接口上配置方法
  2. 在新添加的方法上,使用注解的形式配置sql查询语句
  3. 注解 : @Query
    value :jpql语句 | sql语句
    nativeQuery :false(使用jpql查询) | true(使用本地查询:sql查询)
    是否使用本地查询
  • 方法名称规则查询
    只需要按照Spring Data JPA提供的方法命名规则定义方法的名称,就可以完成查询工作。Spring Data JPA在程序执行的时候会根据方法名称进行解析,并自动生成查询语句进行查询

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)

复杂查询代码举例:
jpql的查询方式

一个单元测试对应一个dao层方法

  • 查询操作:根据客户名称查询客户
@Query(value = "from Customer where custName=?")
  public Customer findCustomer(String custName);
  
  @Test
  public void testFindCustomer(){
      Customer customer =  customerDao.findCustomer("传智播客");
      System.out.println("查询客户信息:"+customer);
  }
  • 多条件查询:根据客户名称和客户id查询客户
/**
    * 多条件查询:根据客户名称和客户id查询客户
    *  对于多个占位符参数
    *  赋值的时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致
    *  可以指定占位符参数的位置
    *  ? 索引的方式,指定此占位的取值来源
    */

  @Query(value = "from Customer where custName=? and custId=?")
  public Customer findCustomerBynNameAndId(String name ,long id);

  @Query(value = "from Customer where custName=?2 and custId=?1")
  public Customer findindIdAndCustomer(long id,String name);

  @Test
  public void testFindCustomerAndId(){
      Customer customer =  customerDao.findCustomerBynNameAndId("传智播客",8);
      System.out.println("查询客户信息:"+customer);
  }

  @Test
  public void testFindIdAndCustomer(){
      Customer customer =  customerDao.findindIdAndCustomer(8,"传智播客");
      System.out.println("查询客户信息:"+customer);
  }
  • 更新操作 :更新4号客户的名称,将名称改为“黑马程序员”
/**
*  @Query : 代表的是进行查询
*  @Modifying 当前执行的是一个更新操作
*/

@Query(value = "update Customer  set custName=?2 where custId=?1")
@Modifying
public int updateCustomer(long id,String name);
}

 @Test
 @Transactional
 @Rollback(value = false)
 public void testUpdateCustomer(){
        int  result =  customerDao.updateCustomer(8,"黑马程序员");
        System.out.println("更新客户信息:"+result);
    }

更新操作注意:

  1. @Transactional 必须有事务
  2. @Rollback(value = false)事务默认回滚,应该关闭事务回滚,否则jpql执行正确,但是数据库依然没有更新数据
sql语句的查询
  • 查询操作( 查询全部的客户)
/**
   *  sql : select * from cst_customer;
   *  Query : 配置sql查询
   *      value : sql语句
   *      nativeQuery : 查询方式
   *          true : sql查询
   *          false:jpql查询
   */
  @Query(value="select * from cst_customer" ,nativeQuery=true)
  public List<Object[]> getAllCustomer();
  
  @Test
  public void findAllCustomer(){
     List<Object[]> list =  customerDao.getAllCustomer();
      for (int i = 0; i < list.size(); i++) {
          System.out.println(Arrays.toString(list.get(i)));
      }
  }
方法名称规则查询
  • 模糊查询
/**
   * 方法名的约定:
   *      findBy : 查询
   *            对象中的属性名(首字母大写) : 查询的条件
   *            CustName
   *            * 默认情况 : 使用 等于的方式查询
   *                  特殊的查询方式
   *
   *  findByCustName   --   根据客户名称查询
   *
   *  再springdataJpa的运行阶段
   *          会根据方法名称进行解析  findBy    from  xxx(实体类)
   *                                      属性名称      where  custName =
   *
   *      1.findBy  + 属性名称 (根据属性名称进行完成匹配的查询=)
   *      2.findBy  + 属性名称 + “查询方式(Like | isnull)”
   *          findByCustNameLike
   *      3.多条件查询
   *          findBy + 属性名 + “查询方式”   + “多条件的连接符(and|or)”  + 属性名 + “查询方式”
   */
   public Customer findByCustNameLikeAndCustLevel(String name,String industry);

  @Test
  public void testFindCustLikeAndCustLevel(){
      Customer customer =  customerDao.findByCustNameLikeAndCustLevel("黑马%","高级");
      System.out.println("模糊查询结果:"+customer);
  }