Spring Data JPA动态查询(多条件and)
Posted Amaris_Lin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; }
以上是关于Spring Data JPA动态查询(多条件and)的主要内容,如果未能解决你的问题,请参考以下文章