Spring Data Jpa接口简介

时间:2022-09-11 14:44:43

Repository接口

public interface Repository<T, ID> {....}

提供了按方法名称的查询方式;

Spring Data Jpa接口简介

 

 

提供了@Query的查询方式

Spring Data Jpa接口简介

Spring Data Jpa接口简介

可能遇到的错误:

1)Caused by: javax.persistence.TransactionRequiredException: Executing an update/delete query(手动加@Transactional解决)

2)如果test方法里加事务注解数据不更新的话,还需要手动加@Rollback(false)解决,自己测试的时候,只加了一个@Transactional就更新成功了.

CrudRepository接口

public interface CrudRepository<T, ID> extends Repository<T, ID> {....}
    public void test1 () {
        JpaUser jpaUser = new JpaUser("名称1","地址1",10,20,2);
        Optional<JpaUser> optionalT = userRespotory.findById(1) ;
        Iterable<JpaUser> list = userRespotory.findAll();
        userRespotory.delete(jpaUser);
        userRespotory.save(jpaUser);//保存or更新
PagingAndSortingRepository接口
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
    Iterable<T> findAll(Sort var1);
    Page<T> findAll(Pageable var1);
}
//测试sort   

public void test1 () { JpaUser jpaUser = new JpaUser("名称1","地址1",10,20,100); Sort sort = new Sort(Sort.Direction.DESC,"id"); Iterable<JpaUser> list = userRespotory.findAll(sort);

//测试page
    public void test1 () {
JpaUser jpaUser = new JpaUser("名称1","地址1",10,20,100);
Pageable pageable = PageRequest.of(0, 2);
Page<JpaUser> page = userRespotory.findAll(pageable);

System.out.println(page.getTotalElements());//总条数
System.out.println(page.getTotalPages());//总页数
System.out.println(page.getContent());//当前页集合
//测试分页+排序
    public void test1 () {
JpaUser jpaUser = new JpaUser("名称1","地址1",10,20,100);
Pageable pageable = PageRequest.of(1, 2,Sort.Direction.DESC,"id","age1");
Page<JpaUser> page = userRespotory.findAll(pageable);

System.out.println(page.getTotalElements());//总条数
System.out.println(page.getTotalPages());//总页数
System.out.println(page.getContent());//当前页集合
JpaRepository接口
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {....}