mercredi 16 décembre 2015

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.

Aucun commentaire:

Enregistrer un commentaire