Gets the value of the query field after the entity is reflected and added to the predicate object array
Publicpredicate Getpredicateand (T entity, root<t> Root, Criteriabuilder CB)throwsintrospectionexception, InvocationTargetException, illegalaccessexception {Try { //getting types by reflectionclass<?> C =Entity.getclass (); //get the fields of a classfield[] Fields =C.getdeclaredfields (); List<Predicate> predicatelist =NewArrayList (); for(Field field:fields) {propertydescriptor pd=NewPropertyDescriptor (Field.getname (), c); //get a Get methodMethod GetMethod =Pd.getreadmethod (); //executes the Get method to return an objectObject Fieldval =Getmethod.invoke (entity); if(Fieldval! =NULL&&!fieldval.equals (0) ) {Path<String> Path =Root.get (Field.getname ()); predicate P=cb.equal (path, fieldval); Predicatelist.add (P); } } returnCb.and (Predicatelist.toarray (Newpredicate[]{})); } Catch(Exception e) {log.error (E.getmessage ()); } return NULL;}
Here is the use method, because the return type is predicate, so it is passed directly as a parameter to the WHERE function of criteriaquery<?>
PublicT FindOne (FinalT entity) { returnGetspecdao (). FindOne (NewSpecification<t>() {@Override Publicpredicate topredicate (root<t> Root, criteriaquery<?>query, Criteriabuilder CB) { Try{Query.where (Getpredicateand (Entity, root, CB)); } Catch(InvocationTargetException e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(introspectionexception e) {e.printstacktrace (); } return NULL; } }); }
Criteriaquery side-by-side conditional query via solid reflection