SpringBoot整合SpringDataJpa 之 Repository

简介

SpringData:SpringData是Spring提供的一个操作数据的框架。而SpringData JPA只是SpringData框架下的一个基于JPA标准操作数据的模块。
SpringData JPA:基于JPA的标准数据进行操作。简化操作持久层的代码。只需要编写接口就可以。

SpringBoot JPA提供的核心接口

  1. Repository接口,提供了:
    • findBy + 属性方法
    • @Query
    • HQL: nativeQuery 默认false
    • SQL: nativeQuery 默认true
    • 更新的时候,需要配合@Modifying使用
  2. CrudRepository接口:继承了Repository 主要提供了对数据的增删改查
  3. PagingAndSortingRepository接口:继承了CrudRepository 提供了对数据的分页和排序,缺点是只能对所有的数据进行分页或者排序,不能做条件判断
  4. JpaRepository接口:继承了PagingAndSortRepository,开发中经常使用的接口,主要继承了PagingAndSortRepository,对返回值类型做了适配
  5. JPASpecificationExecutor接口:提供多条件查询,这个接口单独存在,没有继承以上说的接口

Repository接口提供了:

  • 方法名称命名查询方式
  • 基于@Query注解查询与更新

1、方法名查询

JpaRepository支持接口规范方法名查询,即:如果在接口中定义的查询方法符合它的命名规则,就可以不用写实现。按照Spring Data的规范,查询方法以find | read | get 开头,涉及查询条件时,条件的属性用条件关键字连接。目前支持的关键字如下:

关键字 示例 产生SQL
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)

注意:

  • 条件属性以首字母大写
  • 条件的属性名称与个数要与参数的位置与个数一一对应

JPA框架在进行方法名解析时,会先把方法名多余的前缀截取掉,比如find、findBy、read、readBy、get、getBy,然后对剩下部分进行解析。假如创建如下的查询:findByUserDepUuid(),框架在解析该方法时,首先剔除findBy,然后对剩下的属性进行解析,假设查询实体为Doc。

  1. 先判断userDepUuid (根据POJO 规范,首字母变为小写)是否为查询实体的一个属性,如果是,则表示根据该属性进行查询;如果没有该属性,继续第二步;
  2. 从右往左截取第一个大写字母开头的字符串此处为Uuid),然后检查剩下的字符串是否为查询实体的一个属性,如果是,则表示根据该属性进行查询;如果没有该属性,则重复第二步,继续从右往左截取;最后假设user为查询实体的一个属性;
  3. 接着处理剩下部分(DepUuid),先判断user 所对应的类型是否有depUuid属性,如果有,则表示该方法最终是根据“Doc.user.depUuid” 的取值进行查询;否则继续按照步骤2 的规则从右往左截取,最终表示根据“Doc.user.dep.uuid” 的值进行查询。
  4. 可能会存在一种特殊情况,比如Doc包含一个user 的属性,也有一个userDep 属性,此时会存在混淆。可以明确在属性之间加上"_" 以显式表达意图,比如"findByUser_DepUuid()" 或者"findByUserDep_uuid()"

2、特殊参数

特殊的参数,还可以直接在方法的参数上加入分页或排序的参数,比如:

  • Page findByName(String name, Pageable pageable);
  • List findByName(String name, Sort sort);

Pageable 是spring封装的分页实现类,使用的时候需要传入页数、每页条数和排序规则,比如:

@Test
public void testPageQuery() throws Exception {
    int page=1,size=10;
    Sort sort = new Sort(Direction.DESC, "id");
    Pageable pageable = new PageRequest(page, size, sort);
    userRepository.findALL(pageable);
    userRepository.findByUserName("testName", pageable);
}

3、使用JPA的NamedQueries

方法如下:

  1. 在实体类上使用@NamedQuery,示例如下:
    @NamedQuery(name = “UserModel.findByAge”,query = “select o from UserModel o where o.age >= ?1”)
  2. 在自己实现的DAO的Repository接口里面定义一个同名的方法,示例如下:
    public List findByAge(int age);
  3. 然后就可以使用了,Spring会先找是否有同名的NamedQuery,如果有,那么就不会按照接口定义的方法来解析。

4、使用@Query来指定本地查询

只要设置nativeQuery为true,比如:

@Query(value="select * from tbl_user where name like %?1" ,nativeQuery=true) //基于SQL
public List<UserModel> findByUuidOrAge(String name);

注意:当前版本的本地查询不支持翻页和动态的排序

5、使用命名化参数

使用@Param即可,比如:

@Query(value="select o from UserModel o where o.name like %:nn")  //基于HQL
public List<UserModel> findByUuidOrAge(@Param("nn") String name);

支持更新类的Query语句

添加@Modifying即可,比如:

@Modifying
@Query(value="update UserModel o set o.name=:newName where o.name like %:nn") //基于HQL
public int findByUuidOrAge(@Param("nn") String name,@Param("newName") String newName);

注意:
1:方法的返回值应该是int,表示更新语句所影响的行数
2:在调用的地方必须加事务,没有事务不能正常执行

创建查询的顺序

Spring Data JPA 在为接口创建代理对象时,如果发现同时存在多种上述情况可用,它该优先采用哪种策略呢?

<jpa:repositories> 提供了query-lookup-strategy 属性,用以指定查找的顺序。它有如下三个取值:

  1. create-if-not-found:如果方法通过@Query指定了查询语句,则使用该语句实现查询;如果没有,则查找是否定义了符合条件的命名查询,如果找到,则使用该命名查询;如果两者都没有找到,则通过解析方法名字来创建查询。这是querylookup-strategy 属性的默认值
  2. create:通过解析方法名字来创建查询。即使有符合的命名查询,或者方法通过@Query指定的查询语句,都将会被忽略
  3. use-declared-query:如果方法通过@Query指定了查询语句,则使用该语句实现查询;如果没有,则查找是否定义了符合条件的命名查询,如果找到,则使用该命名查询;如果两者都没有找到,则抛出异常


示例:

准备工作:

实体类:

@Entity
@Table(name = "tb_dept")
@NamedQuery(name = "Dept.findLocByDname",query="select loc from Dept where dname = ?1")
public class Dept {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer deptno;

    @Column
    private String dname;

    @Column
    private String loc;

    //……getter/setter、默认构造方法、全参构造方法
}

第一步:创建Maven项目,添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

第二步:修改application.yml:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db_test?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        enable_lazy_load_no_trans: true
    show-sql: true

第三步:编写接口DeptDao.java:

方法名称必须要遵循驼峰式命名规则,findBy(关键字)+属性名称(首字母大写)+查询条件(首字母大写)

public interface DeptDao extends Repository<Dept,Integer> {
    //接口规范方法名
    List<Dept> findByDname(String dname);

    List<Dept> findByLocContaining(String param);

    List<Dept> findByDeptnoGreaterThan(Integer param);
    
	List<Dept> findByDnameAndLoc(String dname,String loc);
	
	Page<Dept> findAll(Pageable pageable);
	
	//NamedQueries
    String findLocByDname(String dname);  //对应Dept.java中的@NamedQuery注解
    
    //特殊参数
    List<Dept> findByDname(String dname, Sort sort);

    //@Query本地查询
    @Query(value = "select * from dept where deptno = ?1",nativeQuery = true)
    Dept findDeptByDeptno1(Integer deptno);

    //@Param命名化参数
    @Query(value = "select * from dept where deptno = :p",nativeQuery = true)
    Dept findDeptByDeptno2(@Param("p") Integer deptno);

    //更新类的Query
    @Modifying
    @Transactional
    @Query(value = "update Dept dept set dept.dname=:name where dept.deptno=:no")
    int updateDnameByDeptno(@Param("name")String dname,@Param("no")Integer deptno);
}

第四步:提供测试代码:

@RunWith(SpringRunner.class)
@SpringBootTest
@EnableAutoConfiguration
public class DeptDaoTest {
    @Autowired
    private DeptDao deptDao;

    @Test
    public void findByDname() {
        List<Dept> depts = deptDao.findByDname("123");
        depts.forEach(System.out::println);
    }

    @Test
    public void findByLocContaining() {
        List<Dept> depts = deptDao.findByLocContaining("O");
        depts.forEach(System.out::println);
    }

    @Test
    public void findByDeptnoGreaterThan() {
        List<Dept> depts = deptDao.findByDeptnoGreaterThan(20);
        depts.forEach(System.out::println);
    }

    @Test
    public void findByDnameAndLoc(){
        List<Dept> depts = deptDao.findByDnameAndLoc("sales", "chicago");
        depts.forEach(System.out::println);
    }
    
    @Test
    public void findLocByDname(){
        String loc = deptDao.findLocByDname("sales");
        System.out.println(loc);
    }
   
    @Test
    public void findWithPage(){
        Pageable pageable =   PageRequest.of(0, 2, Sort.by("loc"));
        Page<Dept> page = deptDao.findAll(pageable);
        List<Dept> depts = page.getContent();
        depts.forEach(System.out::println);
    }
    
    @Test
    public void findByDnameWithSort() {
        List<Dept> depts = deptDao.findByDname("123", Sort.by("loc"));
        depts.forEach(System.out::println);
    }

    @Test
    public void findDeptByDeptno1(){
        Dept dept = deptDao.findDeptByDeptno1(20);
        System.out.println(dept);
    }

    @Test
    public void findDeptByDeptno2(){
        Dept dept = deptDao.findDeptByDeptno2(30);
        System.out.println(dept);
    }

    @Test
    public void updateDnameByDeptno(){
        int res = deptDao.updateDnameByDeptno("1234",1);
        System.out.println(res);
    }
}
发布了310 篇原创文章 · 获赞 720 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章