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 {
    @Transactional
    @Modifying
    @Query(value="delete from test where id=?1 ",nativeQuery=true)
    int deleteByPrimaryKey(String id);

    
    List findAll(Specification specification);   //传入Specification对象


}

service:

public List getDataIllustrationList(Test test) {
        List test2 = dataIllustrationMapper.findAll(new Specification(){
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List predicates = new ArrayList();
                
                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;
    }

 

转载于:https://www.cnblogs.com/Amaris-Lin/p/7459198.html

你可能感兴趣的:(Spring Data JPA动态查询(多条件and))