Search code examples
hibernatespring-dataspring-data-jpajpqljpa-criteria

Spring Data JPA 'AND' Query combinations


My Entity class has four instance variables:

Ref Id, billing ID, customer ID and profile ID.

All of them are String variables.

I need atleast one of them to be mandatory. I will then be doing a select query.

If more than one values is filled then I want combine them in an 'AND' condition and then do a select query. i.e. if billing ID and customer ID is filled out then select * from ... where billingID ="..." AND customerID = "..."

Similarly if three values are filled then there should be 'AND' condition between three variables.

I have a repository class which extends crud repository.

Is there an easier way to do this apart from writing multiple Query methods i.e. findByBillingID, findByBillingIDAndCustomerID, and so on...


Solution

  • Yes. You can the Criteria and Restrictions to add different criteria to a query. It's functionally identical to using HQL query strings, but it uses an API instead. So, in your case your code can look something like this:

    String ref, billing, customer, profile;
    //get the values for those here
    Criteria crit = session.createCriteria(MyEntity.class);
    if(ref != null){
        crit.addRestriction(Restrictions.equals("ref", ref));
    }
    if(billing != null){
        crit.addRestriction(Restrictions.equals("billing", billing));
    }
    //...etc
    return crit.list();//returns your results