Generic dao methods that use hibernation criteria are wrong, but it feels so right

I currently have one dao that uses common methods and criteria for hibernation to execute almost all of my data (I planned to subclass for 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 because it can be optimized using a database / connection (i.e. parameterized queries), and api criteria should be evaluated at runtime, so Restrictions.eq("name", "NimChimpksy") is not safe at all.

Should I keep a common dao (it's 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.

+4
source share
2 answers

Honestly, I see no problems with your current approach if your requests are simple and straightforward.

Usually, at least in my team, choosing to use HQL vs Criteria is more likely "preferred." HQL is more like SQL, and you can write more concise code. The criteria look 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, this is really a matter of preference, I think). Nevertheless, the criterion can be very useful, because it allows me to build query conditions on the go of the entire batch much easier than HQL, here is 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 want to do something like this in HQL, you will have to dynamically build the HQL query string on the fly, which can make the code a little unpleasant to read.

+3
source

I use a static class for all of my basic Hibernate operations to retrieve, save, update, delete, and works very well.

 public static List getList(Class c, Session session) { return session.createQuery("FROM " + c.getSimpleName()).list(); } 
0
source

Source: https://habr.com/ru/post/1397990/


All Articles