简体   繁体   中英

Hibernate: Criterion. Add Alias to Criterion Object

In Hibernate, is there a way to create an add an Alias to a Criterion object. I have the following to work with:

I have a dynamic search from big Database with many tables. The search has many (25+) optional non-exclusive parameters selected clien-side. This requires the use of the Hibernate Criteria API for managability. In my DAO I have the following method:

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(); 
return response;
}

I need to do a Join with myOtherPojo.class and would like to know if it is possible to add an alias to the Criteria list above.
Somthing like :

restrictionsList.add(... ...createAlias("myOtherPojo.class" , "mop");

then, I need o add other Logical and to this class as above.

You again! ;)

You could pass a collection of entries (like a HashMap<String, String>) and iterate over them to populate your aliases... like this:

Public List<myPojoClass> getDataByCriterion( List<Criterion> restrictionList, HashMap<String,String> aliases) {
Session s = HibernateUtil.currentSession(); 
Criteria c = s.createCriteria(myPojo.class); 
for (Criterion crit : restrictionList){     
    c.add(crit); 
}
for (Entry<String, String> entry : aliases.entrySet()){
    c.createAlias(entry.getKey(), entry.getValue());
}

List<myPojoClass> response = c.list(); 
return response;
}

You could do something similar if you want to change the fetch modes. Of course the calling method needs to know the data model so it can set up the aliases properly, otherwise you can get errors at runtime.

from what I know there is now way to create joins without instance of Criteria. I suggest you create some wrapper for criteria which would contain criteria and alias definition if necessary and then use Criteria as visitor (like from this Pattern)

interface CriterionWrapper {
    void visit(Criteria c);
}
class OnlyCriterionWrapper implements CriterionWrapper {
    private Criterion c;
    public void visit(Criteria c){c.add(c);}
}
class CriterionWrapper implements CriterionWrapper{
    private Criterion c;
    private String whateverIsNeededToCreateAlias
    public void visit(Criteria c){
        c.createAlias(whateverIsNeededToCreateAlias); 
        c.add(c);
    }
}

and then pass List as parameter to your getDataByCriterion() method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM