Criteriaquery side-by-side conditional query via solid reflection

Source: Internet
Author: User
Tags findone

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.