jpa的各种Repository使用示例速查如下:
1. 使用jpa的 CrudRepository 基本查询
/**
* @author yawn < http://jvm123.com >
* 2019/9/15 15:18
*/
public interface PersonCrudRepo extends CrudRepository<Person, Long> {
}
2. 使用jpa的 PagingAndSortingRepository 分页查询和排序
/**
* @author yawn < http://jvm123.com >
* 2019/9/15 15:18
*/
public interface PersonPageSortRepo extends PagingAndSortingRepository<Person, Long> {
}
3. 使用jpa的 Repository 自定义声明式查询方法
/**
* @author yawn < http://jvm123.com >
* 2019/9/15 15:18
*/
public interface PersonQueryRepo extends Repository<Person, Long> {
// declare query method
// 声明式查询方法
// 1. count 计数
long countByName(String name);
// 2. get/find/stream/query/read 查询
Person readFirstByAge(int age);
// 3. delete/remove 删除
@Transactional
int deleteById(long id);
}
4. 使用jpa的 JpaRepository 使用hql、jpql或sql查询,@Query等注解
/**
* @author yawn < http://jvm123.com >
* 2019/9/15 17:02
*/
public interface PersonHqlDao extends JpaRepository<Person, Long> {
// 使用hql 或者 jpql 查询
@Query("from Person where name = ?1 order by id desc")
List<Person> listByName(String name);
// 前几种方法中均未介绍update操作,要完成update操作,可使用以下方法
// 更新时需要加上 @Transactional 和 @Modifying
@Transactional
@Modifying // QueryExecutionRequestException: Not supported for DML operations
@Query("update Person set name=?2 where id=?1")
int updateNameById(long id, String name);
}