SpringData JPA利用Specification实现多条件查询

SpringData JPA遵循Eric Evans在Domain Driver Design一书中的规范,让你可以使用编程方式来构建多条件查询。

开始

创建实体类:Blog

@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;

}

BlogDao继承JpaSpecificationExecutor接口

public interface BlogDao extends JpaRepository<Blog, Long>, JpaSpecificationExecutor<Blog> {
}

继承JpaSpecificationExecutor之后,便能够使用其中提供Specification相关的方法
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接口对象,而且可以注意到这个接口中有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

参考:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#reference

转载至:https://www.cnblogs.com/summerday152/p/14182138.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LuckyTHP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值