基础的 Repository 提供了最基本的数据访问功能,其几个子接口则扩展了一些功能。它们的继承关系如下:
Repository: 是 spring Data 的一个核心接口,它不提供任何方法,开发者需要在自己定义的接口中声明需要的方法
仅仅是一个标识,表明任何继承它的均为仓库接口类,方便Spring自动扫描识别,
@Indexed public interface Repository<T, ID> { }
T :实体类名 ID : 主键类型
CrudRepository: 继承 Repository,实现了一组 CRUD 相关的方法
@NoRepositoryBean public interface CrudRepository<T, ID> extends Repository<T, ID> { <S extends T> S save(S entity); <S extends T> Iterable<S> saveAll(Iterable<S> entities); Optional<T> findById(ID id); boolean existsById(ID id); Iterable<T> findAll(); Iterable<T> findAllById(Iterable<ID> ids); long count(); void deleteById(ID id); void delete(T entity); void deleteAll(Iterable<? extends T> entities); void deleteAll(); }
PagingAndSortingRepository: 继承 CrudRepository,实现了一组分页排序相关的方法
public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID>
Iterable<T> findAll(Sort sort); Page<T> findAll(Pageable pageable); }
使用举例:
如果要在以20为一页的结果中,获取第2页结果,则如下使用:
Page<User> users = repository.findAll(new PageRequest(1, 20));
JpaRepository: 继承 PagingAndSortingRepository,实现一组 JPA 规范相关的方法
自定义的 XxxxRepository 需要继承 JpaRepository,这样的 XxxxRepository 接口就具备了通用的数据访问控制层的能力。
JpaSpecificationExecutor: 不属于Repository体系,实现一组 JPA Criteria 查询相关的方法 。
直接在接口中定义方法,如果符合规范,则不用写实现。目前支持的关键字写法如下:
// 级联查询,查询address的id等于条件值/ List<Person> findByAddressId(Integer addressId);
运行测试方法
/** 测试findByAddressId方法 */ @Test PersonDao personDao = ctx.getBean(PersonDao.class); // 查出地址id为1的person集合 List<Person> list = personDao.findByAddressId(1); for (Person person : list) { System.out.println(person.getName() + "---addressId=" + person.getAddress().getId()); } }
// 自定义的查询,直接写jpql语句; 查询id<? 或者 名字 like?的person集合 @Query("from Person where id < ?1 or name like ?2") List<Person> testPerson(Integer id, String name); // 自定义查询之子查询,直接写jpql语句; 查询出id最大的person @Query("from Person where id = (select max(p.id) from Person as p)") Person testSubquery();
一个特殊情况,那就是自定义的Query查询中jpql语句有like查询时,可以直接把%号写在参数的前后,这样传参数就不用把%号拼接进去了。使用案例如下,调用该方法时传递的参数直接传就ok。
//可以通过自定义的 JPQL 完成 UPDATE 和 DELETE 操作. 注意: JPQL 不支持使用 INSERT //在 @Query 注解中编写 JPQL 语句, 但必须使用 @Modifying 进行修饰. 以通知 SpringData, 这是一个 UPDATE 或 DELETE 操作 //UPDATE 或 DELETE 操作需要使用事务, 此时需要定义 Service 层. 在 Service 层的方法上添加事务操作. //默认情况下, SpringData 的每个方法上有事务, 但都是一个只读事务. 他们不能完成修改操作! @Modifying @Query("UPDATE Person p SET p.name = :name WHERE p.id < :id") int updatePersonById(@Param("id")Integer id, @Param("name")String updateName);
本文参考博客:http://www.cnblogs.com/zeng1994/
Spring-data-jpa 笔记(二) Repository 详解
原文:https://www.cnblogs.com/qq99514925/p/10668235.html