DAO pattern - where do transactions fit in?

前端 未结 5 1495
独厮守ぢ
独厮守ぢ 2021-02-05 04:54

So I\'ve got this generic DAO thing going on and at face value it appears to be ok. It\'s basically modeled after the CaveatEmptor sample application from the Hibernate guys.

5条回答
  •  执笔经年
    2021-02-05 05:38

    In the past I've put the transaction logic in the root DAO for a hierarchy of DAOs that match to a hierarchy of Objects in your model that represent a single solid entity in the system.

    I.e., if you have and X that has many Ys, and you want to store and retrieve Xs and their Ys at the same time as a single compound object, then your DAO for X should also call the DAO for Y. Then you can put a transaction around everything in your add() and update() methods in the DAO for X - and even make the Y DAO package private to hide it from your main business logic. I.e., instead of business logic:

    XDAO xDAO = new XDAO(conn);
    xDAO.startTransaction();
    boolean success = xDAO.add(x);
    if (success)
        for (Y y : x.getYs()) {
            success = YDAO.add(y);
            if (!success) break;
        }
    if (success)
        xDAO.commit();
    else
        xDAO.rollback();
    

    You would just have:

    XDAO xDAO = new XDAO(conn);
    xDAO.add(x);
    

    (with the success / commit / rollback logic internal to that DAO)

    However this doesn't cover every situation, and yours may be different (for example mine works with JDBC, I don't know how Hibernate works or if it is possible there).

提交回复
热议问题