General or specific DAO to record delivery with in

2019-03-02 06:37发布

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 to creating the DAO and service layer. I want to create a method that can add a new delivery. In my delivery table i have Product Id and Customer Id which both are mapped to their own tables that contain Product Name, Product Type and Customer Name, Customer Country respectively.

The part that I have trouble with is that I want the end user to record a delivery by entering the product type, product name, customer name, customer country and date. Do I,

(1) Create a DAO with a method for adding a new delivery that includes these objects

or

(2) Create a DAO that just persist a general object to the DB and then use a service method to implement the DAO for each separate object?

Thank you for your help!

/D

1条回答
戒情不戒烟
2楼-- · 2019-03-02 07:04

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.

查看更多
登录 后发表回答