Spring Data JPA动态查询(多条件and)

时间:2023-03-09 16:00:58
Spring Data JPA动态查询(多条件and)

entity:

@Entity
@Table(name = "data_illustration")
public class Test { @Id
@GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
@GeneratedValue(generator = "uuid")
private String id; @Column(name = "fileId")
private String fileid; private String title; @Column(name = "WFState")
private String wfstate; @Column(name = "issueNo")
private String issueno; private String format; //对应得set、get方法省略 }

mapper:

public interface IllustrationMapper extends JpaRepository<Test, String> {
@Transactional
@Modifying
@Query(value="delete from test where id=?1 ",nativeQuery=true)
int deleteByPrimaryKey(String id); List<Test> findAll(Specification<CsdbDataIllustration> specification); //传入Specification对象 }

service:

public List<Test > getDataIllustrationList(Test test) {
List<Test > test2 = dataIllustrationMapper.findAll(new Specification<Test >(){
@Override
public Predicate toPredicate(Root<Test > root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<Predicate>(); if(StringUtils.isNotBlank(test.getId())){
predicates.add(cb.equal(root.get("id"), test.getId()));
} if(StringUtils.isNotBlank(test.getFileid())){
predicates.add(cb.equal(root.get("fileid"), test.getFileid() ));
}
if(StringUtils.isNotBlank(test.getTitle())){
predicates.add(cb.equal(root.get("title"), test.getTitle() ));
}
if(StringUtils.isNotBlank(test.getWfstate())){
predicates.add(cb.equal(root.get("wfstate"), test.getWfstate() ));
}
if(StringUtils.isNotBlank(test.getIssueno())){
predicates.add(cb.equal(root.get("issueno"), test.getIssueno() ));
}
if(StringUtils.isNotBlank(test.getFormat())){
predicates.add(cb.equal(root.get("format"), test.getFormat() ));
} return cb.and(predicates.toArray(new Predicate[predicates.size()])); //将上面满足条件的项用and拼接起
                                                   //来进行查询,当然此处也可以改为or或者like等等,视情况而定
} });
return test2;
}