简体   繁体   中英

Is there a good design pattern to execute 2 methods from different DAO in a single transaction?

I have two DAOs, InvoiceDao and InvoiceItemDao and i have the method update in each one. This is the update method in the Dao:

public void update(E... es){
    Session s = null;
    try {
        s = ConnectDb.getSession();
        s.getTransaction().begin();
        for (E e : es) {
            s.update(e);
        }
        s.getTransaction().commit();
        for (E e : es) {
            s.refresh(e);
        }
    } catch(Exception ex){
        ex.printStackTrace();
        try { if (s != null) s.getTransaction().rollback(); } catch (Exception ignored) {}
        throw ex;
    } finally {
        try { if (s != null) s.close(); } catch (Exception ignored) {}
    }
}

As you can see, the method begins and commits/rollbacks the transaction manually. So if i need to update the Invoice and its Items using this approach, two transactions will begin and finish.

Is there a good way to to this, without having to create a method updateInvoiceAndItsItems(Invoice invoice, InvoiceItems... items) ?

UPDATE This is a desktop app, so, no automatic transaction management.

Have you considered using something like Commands and a CommandProcessor ?

http://wiki.hsr.ch/APF/files/CommandProcessor.pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM