Spring Boot的进阶和高级 - Go语言中文社区

Spring Boot的进阶和高级




一、Repository接口

Repository接口是Spring Data的核心接口,不提供任何方法。

public interface Repository<T,ID extends Serializable>{ }

@RepositoryDefinition注解的使用

1

二、Repository子接口

CrudRepository:继承Repository,实现了CRUD相关的方法;

PagingAndSortingRepository:继承CrudRepository,实现了分页排序相关的方法;

JpaRepository:继承PagingAndSortingRepository,实现JPA规范相关的方法;

Repository中查询方法定义规则和使用

Spring Data中查询方法名称的定义规则

使用Spring Data完成复杂查询方法名称的命名

2

3

eg:where name like ?% and age<?
方法名:findByNameStartingWithAndAgeLessThan(String name,Integer age)
where name in(?,?....)  or age<?
findByNameInOrAgeLessThan(List<String>names,Integer age);
对于按照方法命名规则来使用,有弊端:
1)方法名会比较长:约定大于配置
2)对于一些复杂的查询,是很难实现
通过@Query解决该弊端;

三、@Query注解

在Repository方法中使用,不需要遵循查询方法命名规则

只需要将@Query定义在Repository中的方法之上即可

命名参数及索引参数的使用

本地查询

源码:

eg:查询的是实体类,而非库表
@Query("select o from Employee o where id = {select max(id) from Employee t1}")
public Employee getEmployeeByMaxId();
eg:
@Query("select o from Employee o where o.name?1 and o.age=2?")
public List<Employee> queryParams(String name,Integer age);
eg:如果使用 =:方式获取参数,必须添加注解@Param
@Query("select o from Employee o where o.name=:name and o.age=:age")
方法名:queryParams(@Param("name")String name,@Param("age")Integer age);
eg:
@Query("select o from Employee o where o.name like %?1%")
public List<Employee> queryLike(String name); 
eg:原生查询方法,需要将原生查询方法设置为true,并且查询的是库表,
@Query(nativeQuery = true , value = "select count(1) from employee")
public long getCount();

四、更新及删除操作整合事物

@Modifying注解使用

@Modifying结合@Query注解执行更新操作

@Transactional在Spring Data中的使用
eg:需添加@Modifying注解,允许修改,这样还是无法操作,新建一个Service进行事物操作
@Modifying
@Query("update Employee o set o.age = :age where o.id = :id")
public void updata(@Param("id")Integer id,@Param("age")Integer age);
Service:需添加事物
@Transactional(javax.transaction)
public void update(Integer id,Integer age){ }

事物在Spring data中的使用:

  1. 事物一般是在Service层
  2. @Query、@Modifying、@Transactional的综合使用

五、CrudRepository接口

4

public interface EmployeeCrudRepository extends CrudRepository<Employee,Integer>{}

需要进行事物操作的,需要在Service层进行操作;

5

六、PagingAndSortingRepository接口

该接口包含分页和排序的功能;

带排序的查询:findAll(Sort sort)

带排序的分页查询:findAll(PageAble pageable)

eg:分页
分页

eg:排序
排序

七、JPARepository接口

6

八、JpaSpecificationExecutor接口

Specification封装了JPA Criteria查询条件

7

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/An1090239782/article/details/81179312
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 22:08:41
  • 阅读 ( 1036 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢