Reputation: 47300
Currently I have one dao, that uses generic methods and hibernate criteria to perform nearly all my data access (I planned to subclass for the more complex things later), it looks like this :
public <T> List<T> getAll(final Class<T> type){
final Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(type);
return crit.list();
}
public <T> List<T> getFieldEq(final Class<T> type, final String propertyName, final Object value){
final Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(type);
crit.add(Restrictions.eq(propertyName, value));
return crit.list();
}
However, HQL is preferable as it can optimized by the database/connection (i.e. parametrized queries), while the criteria api has to be evaluated at runtime, so Restrictions.eq("name", "NimChimpksy")
is not error safe at all.
Should I keep the generic dao (it feels nice to have only one dao), or just implement a common interface and use hql in a separate dao for each of my domain objects.
Upvotes: 4
Views: 6320
Reputation: 5554
I am using a static class for all my basic Hibernate get, save, update, delete operations and it works pretty well.
public static List getList(Class c, Session session)
{
return session.createQuery("FROM " + c.getSimpleName()).list();
}
Upvotes: 0
Reputation: 40176
Frankly speaking, I don't see any problem with your current approach, assuming your queries are this simple and straightforward.
Usually, at least in my team, the choice of using HQL vs Criteria is more of a "preference" thing. HQL looks more like SQL and you can write more compressed code. Criteria looks more OO for some developers.
In my case, I tend to use HQL because it allows me to write much shorter and cleaner code for complex queries (again, it's really a matter of preference, I believe). However, Criteria can be very useful too because it allows me to construct query conditions on the fly whole lot more easier than HQL, here's a very simple example:-
public void doIt(String s1, String s2, String s3){
...
if (/*some s1 condition*/) {
crit.add(Restrictions.eq("s1", s1));
}
if (/*some s2 condition*/) {
crit.add(Restrictions.like("s2", s2 + "%"));
}
if (/*some s3 condition*/) {
crit.add(Restrictions.ne("s3", s3));
}
return crit.list();
}
Imagine if you were to do something like this in HQL, you will have to dynamically construct the HQL query string on the fly, which can make the code a little nasty to read.
Upvotes: 3