Spring Data JPA 查询
方法命名查询、@Query、分页、更新
定义 Repository
public interface PostRepository extends JpaRepository<Post, Long> {
Optional<Post> findBySlug(String slug);
List<Post> findByTypeAndStatusOrderByCreatedAtDesc(String type, String status);
}
方法命名规则
| 写法 | 含义 |
|---|---|
| findByTitle | where title = ? |
| findByTitleLike | where title like ? |
| findByStatusAndType | and 组合 |
| findByCreatedAtAfter | where created_at > ? |
| countByStatus | select count(*) where status = ? |
| existsBySlug | 是否存在 |
自定义 JPQL
@Query("SELECT p FROM Post p WHERE p.title LIKE %:kw% OR p.tags LIKE %:kw%")
List<Post> search(@Param("kw") String kw);
更新/删除要加 @Modifying
@Modifying
@Query("UPDATE Post p SET p.viewCount = p.viewCount + 1 WHERE p.id = :id")
void incView(@Param("id") Long id);
常用方法
repo.findById(1L); repo.findAll(); repo.save(e); repo.deleteById(1L); repo.count();
repo.findAllByOrderByCreatedAtDesc(); // 排序