springBootJpa的基本查询使用

1、Jpql语句的查询

jpql : jpa query language (jpq查询语言)
特点:语法或关键字和sql语句类似
查询的是类和类中的属性

关键字:@Query
查询方法

@Query(value = "from 数据表对应的实体类名 where 查询条件")

  /* *
     *  对于多个占位符参数
     *      赋值的时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致
     *
     *  可以指定占位符参数的位置
     *      ? 索引的方式,指定此占位的取值来源
     */
    @Query(value = "from Customer where custName = ?2 and custId = ?1")
    public Customer findCustNameAndId(Long id,String name);
更新方法 需要额外@Modifying注解

并且需要添加事务和 @Rollback(value = false)
@Query(value = " update 数据表对应的实体类名 set 属性 = ? where 查询条件 ")

  /* *
     *  sql  :update cst_customer set cust_name = ? where cust_id = ?
     *  jpql : update Customer set custName = ? where custId = ?
     *
     *  @Query : 代表的是进行查询
     *      * 声明此方法是用来进行更新操作
     *  @Modifying
     *      * 当前执行的是一个更新操作
     *
     */
    @Query(value = " update Customer set custName = ?2 where custId = ?1 ")
    @Modifying
    public void updateCustomer(long custId,String custName);

2、sql语句的查询

1.特有的查询:需要在dao接口上配置方法
2.在新添加的方法上,使用注解的形式配置sql查询语句
3.注解 : @Query
value :jpql语句 | sql语句
nativeQuery :false(使用jpql查询) | true(使用本地查询:sql查询)
是否使用本地查询

@Query(value="select * from cst_customer where cust_name like ?1",nativeQuery = true)

 /*  *
     * 使用sql的形式查询:
     *     查询全部的客户
     *  sql : select * from cst_customer;
     *  Query : 配置sql查询
     *      value : sql语句
     *      nativeQuery : 查询方式
     *          true : sql查询
     *          false:jpql查询
     */
    @Query(value = " select * from cst_customer" ,nativeQuery = true)
    @Query(value="select * from cst_customer where cust_name like ?1",nativeQuery = true)
    public List findSql(String name);

3、方法命名规则查询

是对Jpql查询,更加深入的封装。
只需要按照Spring Data JPA提供的方法命名规则定义方法的名称,就可以完成查询工作。

/**
     * 方法名的约定:
     *      findBy : 查询
     *            对象中的属性名(首字母大写) : 查询的条件
     *            CustName
     *            * 默认情况 : 使用 等于的方式查询
     *                  特殊的查询方式
     *
     *  findByCustName   --   根据客户名称查询
     *
     *  再springdataJpa的运行阶段
     *          会根据方法名称进行解析  findBy    from  xxx(实体类)
     *                                      属性名称      where  custName =
     *
     *      1.findBy  + 属性名称 (根据属性名称进行完成匹配的查询=)
     *      2.findBy  + 属性名称 + “查询方式(Like | isnull)”
     *          findByCustNameLike
     *      3.多条件查询
     *          findBy + 属性名 + “查询方式”   + “多条件的连接符(and|or)”  + 属性名 + “查询方式”
     */
    public Customer findByCustName(String custName);


    public List findByCustNameLike(String custName);

    //使用客户名称模糊匹配和客户所属行业精准匹配的查询
    public Customer findByCustNameLikeAndCustIndustry(String custName,String custIndustry);

开启控制台输出sql语句:spring.jpa.show-sql=true

你可能感兴趣的:(springBootJpa的基本查询使用)