General or specific DAO to record delivery with information from multiple tables?

前端 未结 1 747
你的背包
你的背包 2021-01-25 13:04

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

相关标签:
1条回答
  • 2021-01-25 13:45

    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.

    0 讨论(0)
提交回复
热议问题