码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-08-31 17:13:58      阅读:461      评论:0      收藏:0      [点我收藏+]

标签:rom   inter   modify   generic   arraylist   对象   pos   div   return   

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)

标签:rom   inter   modify   generic   arraylist   对象   pos   div   return   

原文地址:http://www.cnblogs.com/Amaris-Lin/p/7459198.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!