社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
Repository接口是Spring Data的核心接口,不提供任何方法。
public interface Repository<T,ID extends Serializable>{ }
@RepositoryDefinition注解的使用
CrudRepository:继承Repository,实现了CRUD相关的方法;
PagingAndSortingRepository:继承CrudRepository,实现了分页排序相关的方法;
JpaRepository:继承PagingAndSortingRepository,实现JPA规范相关的方法;
Repository中查询方法定义规则和使用
Spring Data中查询方法名称的定义规则
使用Spring Data完成复杂查询方法名称的命名
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解决该弊端;
在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中的使用:
public interface EmployeeCrudRepository extends CrudRepository<Employee,Integer>{}
需要进行事物操作的,需要在Service层进行操作;
该接口包含分页和排序的功能;
带排序的查询:findAll(Sort sort)
带排序的分页查询:findAll(PageAble pageable)
eg:分页
eg:排序
Specification封装了JPA Criteria查询条件
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!