The premise of this article:
two ways to implement a simple dynamic query using spring Data Jpa in Springboot
The second method in this article implements specification this method only applies to one object for a fixed field query, and the following is overridden by generics:
Importjava.util.List;ImportJavax.persistence.criteria.CriteriaBuilder;ImportJavax.persistence.criteria.CriteriaQuery;Importjavax.persistence.criteria.Predicate;ImportJavax.persistence.criteria.Root;ImportJavax.persistence.metamodel.SingularAttribute;Importorg.springframework.data.jpa.domain.Specification;/***create by YYC June 12, 2017 pm 3:26:25*/ Public classSpecificationutil { Public Static<t, y> specification<t> getspec (singularattribute<?SuperT,y>SA, Integer parameter) { return NewSpecification<t>() {@SuppressWarnings ("Unused") @Override Publicpredicate topredicate (root<t> Root, criteriaquery<?>query, Criteriabuilder CB) {predicate P1=NULL; if(-1! =parameter) {predicate P2=cb.equal (Root.get (SA), parameter); if(P1! =NULL) {P1=Cb.and (P1, p2); } Else{P1=P2; } } returnP1; } }; } Public Static<t, y> specification<t> getSpec2 (singularattribute<?SuperT,y> sa,list<integer>parameters) { return NewSpecification<t>() {@Override Publicpredicate topredicate (root<t> Root, criteriaquery<?>query, Criteriabuilder CB) {predicate P1=NULL; if(NULL!=parameters) {predicate P2=NULL; for(Integer parameter:parameters) {P2=cb.equal (Root.get (SA), parameter); if(P1! =NULL) {P1=Cb.and (P1, p2); }Else{P1=P2; } } } returnP1; } }; }}
Using Java Generics, the basic query method is implemented.
The first method in the class Getspec (singularattribute<? Super t,y> SA, Integer parameter) passes in a singularattribute and the corresponding int parameter;
The second method of GETSPEC2 (SINGULARATTRIBUTE<? super t,y> sa,list<integer> parameters) Pass in a singularattribute and a corresponding set of int parameters.
The first method applies to cases where there is only one int condition on a single table, and the second method applies to cases where there are multiple int conditions on a single table.
Use:
Use of the first method:
Specificationutil.getspec (Company_.accode, AreaCode) is called this method, according to areacode this field to query, The second parameter of the Finall method is about paging and sorting.
Repository.findall (specificationutil.getspec (Company_.accode, AreaCode), newNew Sort (DIRECTION.ASC, "Comid"));
Use of the second method:
SPECIFICATIONUTIL.GETSPEC2 (Waterdtudev_.comid, companyids) query based on multiple comid, Comid is an integer, Companyids is a list <Integer>.
Repository.findall (specificationutil.getspec2 (Waterdtudev_.comid, Companyids)
New New Sort (DIRECTION.ASC, "Wdid"));
Spring Data JPA implements a common specification method for simple dynamic queries