之前已经有写过在JPA框架中利用@Query的自定义sql中进行逻辑判断,可以使用if和case when两种方法,但是如果数据量大,这种就会影响效率和不方便日后维护,所以,今天我们使用Specification进行多条件动态,
Spring has a wrapper around the JPA criteria API (that uses predicates) and is called the specification API.
先编写规范,如果为null,就返回null,跟if 逻辑一样
order by
or
由于需要子对象的属性查找到该对象,所以需要连表
之后定义完就可以具体使用,该类不用加任何注解,定义个静态,方便使用
之后通过 Specification. where或者 .and调用,使用find方法使用
如果需要分页需要实现 Pageable
简单好用,使用Specification 需要在Repository继承JpaSpecificationExecutor