Hibernate: Criterion. is it possible to build a Restrion List and then later add it to a Critera object

StackOverflow https://stackoverflow.com/questions/11525841

Question

I have a dynamic search with 25 optional parameters. HQl is not an option. I am using the Criterion API. I have DAO methods that I would like to accept a 'Restriction' List that I can build in my service layer such that, when I call my DAO method from the service as follows:

Lits<myPojoClass> = myDAO.getDataByCriterion( <?Restriction List?> )

myDAO.getDataByCriterion could consume the 'Restriction List' as follows:

inside the myDAO class

Public List<myPojoClass> getDataByCriterion( <?Restriction List?> restrictionList) {
    Session s = HibernateUtil.currentSession();
    Criteria c = s.createCriteria(myPojo.class)
                  .add(Restrictions ( <?Restriction List?>  );  //attach the list here
    List<myPojoClass> response = c.list();

It seems like somthing you should be able to do. Is it possible to add the restrictions passed into the DAO method

Was it helpful?

Solution

Yes, it's possible. Your Restriction List should be a regular List of Criterion objects (i.e., List <Criterion>). Just to be clear, if you add them all like your sample code, you're gonna be doing a conjunction (a series of logical ANDs).

Adding my suggestion to your code gives this:

Public List<myPojoClass> getDataByCriterion( List<Criterion> restrictionList) {
Session s = HibernateUtil.currentSession();
Criteria c = s.createCriteria(myPojo.class);
for (Criterion crit : restrictionList){
    c.add(crit);
}

List<myPojoClass> response = c.list();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top