SpringData JPA遵循Eric Evans在Domain Driver Design
一書中的規范,讓你可以使用編程方式來構建多條件查詢。
快速開始
關於SpringBoot與JPA的快速整合,已經在這篇文章中寫的非常詳細:SpringBoot整合Spring Data JPA,一些配置部分就不再贅述了,我們直接創建一個條件豐富一些的實體類做測試。
創建實體類
@Entity(name = "t_blog")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 文章名稱
*/
private String name;
/**
* 作者
*/
private String author;
/**
* 狀態, 0代表未發布, 1代表已發布
*/
private Integer status;
/**
* 發布時間
*/
@Column(name = "publish_time")
private Date publishTime;
/**
* 更新時間
*/
@Column(name = "update_time")
private Date updateTime;
}
繼承JpaSpecificationExecutor接口
public interface BlogDao extends JpaRepository<Blog, Long>, JpaSpecificationExecutor<Blog> {
}
繼承JpaSpecificationExecutor
之后,便能夠使用其中提供Specification
相關的方法:
public interface JpaSpecificationExecutor<T> {
Optional<T> findOne(@Nullable Specification<T> spec);
List<T> findAll(@Nullable Specification<T> spec);
Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);
List<T> findAll(@Nullable Specification<T> spec, Sort sort);
long count(@Nullable Specification<T> spec);
}
Specification接口
可以看到,他們都需要一個Specification接口對象,而且可以注意到這個接口中有Java8新增的接口規范,如static方法、default方法,以及僅有一個抽象方法,可以作為函數式接口,傳入Lambda表達式簡化書寫。
這些方法的用法其實見名知義對吧。
public interface Specification<T> extends Serializable {
long serialVersionUID = 1L;
static <T> Specification<T> not(@Nullable Specification<T> spec) {
return spec == null //
? (root, query, builder) -> null //
: (root, query, builder) -> builder.not(spec.toPredicate(root, query, builder));
}
static <T> Specification<T> where(@Nullable Specification<T> spec) {
return spec == null ? (root, query, builder) -> null : spec;
}
default Specification<T> and(@Nullable Specification<T> other) {
return SpecificationComposition.composed(this, other, CriteriaBuilder::and);
}
default Specification<T> or(@Nullable Specification<T> other) {
return SpecificationComposition.composed(this, other, CriteriaBuilder::or);
}
@Nullable
Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder);
}
復雜查詢
@Test
public void findByExample() {
Specification<Blog> specification = new Specification<Blog>() {
@Override
public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new LinkedList<>();
predicates.add(cb.equal(root.get("status"), 1)); // 查詢status狀態為1
predicates.add(cb.like(root.get("author"), "%summer%")); // author名稱中存在summer
predicates.add(cb.between(root.get("publishTime"), // 發布時間7天前至今
Date.from(Instant.now().minus(Duration.ofDays(7))), new Date()));
return query.where(predicates.toArray(new Predicate[0])).getRestriction();
}
};
// 按照條件查詢,並按照publish_time升序
List<Blog> blogs
= blogDao.findAll(specification, Sort.by(Sort.Direction.ASC, "publishTime"));
blogs.forEach(System.out::println);
}
最后的查詢語句如下:
select id, author, name,publish_time,status,update_time from t_blog
where status = 1 and (author like ?)
and (publish_time between ? and ?)
order by publish_time asc