0

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...

Anshuman Tripathy
  • 113
  • 1
  • 3
  • 12

1 Answers1

1

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
Yserbius
  • 1,375
  • 12
  • 18
  • Could you tell me how I can do it in the context of Spring data JPA criteria API – Anshuman Tripathy Feb 14 '18 at 18:25
  • Instead of using a CrudRepository, write your own. Create an interface (call it `CustomerDao` or whatever) with the methods, then create a class that implements (`CustomerDaoImpl`) it and annotate it with `@Repository`. The implementation should have a field of type `SessionFactory` annotated with `@Autowired`. Your XML or Java configuration file also needs to define `SessionFactory` similarly to how you set up your repositories. – Yserbius Feb 14 '18 at 19:05
  • Did exactly as you asked and it works perfectly. Configuring the SessionFactory creator in the config file was a bit of a task, but it worked out. Thanks. – Anshuman Tripathy Feb 14 '18 at 21:58