I am creating a web application that lets the user store and retrieve information from a DB through a GUI using spring and hibernate.
I have gotten stuck when it comes t
here is a snippet of my generic dao, which I inject into each service layer class.
@Component("Dao")
public class Dao implements IDao {
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
@Override
public <T> T save(final T o){
return (T) sessionFactory.getCurrentSession().save(o);
}
@Override
public void delete(final Object object) {
sessionFactory.getCurrentSession().delete(object);
}
@Override
public <T> T get(final Class<T> type, final Long id) {
return (T) sessionFactory.getCurrentSession().get(type, id);
}
@Override
public <T> List<T> getFieldsEq(final Class<T> type, final Map<String, Object> restrictions) {
final Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(type);
for (Map.Entry<String, Object> entry : restrictions.entrySet()) {
crit.add(Restrictions.eq(entry.getKey(), entry.getValue()));
}
return crit.list();
}
}
Which can hen be used in your service layer like so :
@Transactional(readOnly = true)
public List<City> getCities() {
return dao.getAll(City.class);
}
And of course you could extend the dao for specific complex queries. Having one generic dao obeys single point of responsibility principle, DRY, and makes it easier to test. The transactions should be on serivce layer and directly relate to units of work.