【问题标题】:Is there a good design pattern to execute 2 methods from different DAO in a single transaction?是否有一个好的设计模式可以在单个事务中执行来自不同 DAO 的 2 个方法?
【发布时间】:2015-12-16 16:57:37
【问题描述】:

我有两个 DAO,InvoiceDao 和 InvoiceItemDao,每个都有 update 方法。 这是Dao中的update方法:

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) {}
    }
}

如您所见,该方法开始并手动提交/回滚事务。因此,如果我需要使用这种方法更新Invoice 及其Items,两个事务将开始和结束。

有没有一种好方法可以做到这一点,而不必创建方法updateInvoiceAndItsItems(Invoice invoice, InvoiceItems... items)

更新 这是一个桌面应用程序,因此没有自动事务管理。

【问题讨论】:

  • 使用 Java EE 容器或 Spring,让您以声明方式处理事务。它不应该比使用@Transactional 注释服务方法更难,并从您的Java 代码中删除所有手动事务处理。 Spring可用于桌面应用程序。
  • 对上一条评论的补充:使用设计 OneToMany/OneToOne 关系,以便持久层为您处理。
  • 我同意 JB Nizet 的观点,使用像 Spring 这样的内置事务管理工具的服务层框架。

标签: java hibernate design-patterns transactions


【解决方案1】:

您是否考虑过使用CommandsCommandProcessor 之类的东西?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-17
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多