使用DAO进行事务管理 [英] Transaction management with DAOs

查看:515
本文介绍了使用DAO进行事务管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java应用程序的DAO层中,我有两个DAO类 EmployeeDAO BankDAO 。我需要控制/处理他们的数据库事务。我使用连接池来获取数据库连接。

In my Java application's DAO layer I have two DAO classes EmployeeDAO and BankDAO. I need to control/handle their database transactions. I use connection pooling to get database connections.

EmployeeDAO类:

EmployeeDAO class:

public class EmployeeDAO {
    String name;
    String empCode;
    int age;

    // Getters & Setters
}

BankDAO类:

public class BankDAO {
    String bankName;
    String acNo;
    String empCode;

    // Getters & Setters
}

假设我要存储与员工和银行账户相关的详细信息该员工在两个数据库表中。首先,我保存员工,然后保存银行详细信息,如果发生错误 我需要回滚完成交易。

Let's say I am going to store an Employee and Bank account details related to that employee in two database tables. First I save employee and second I save bank details and if an error occurs when storing bank details I need to rollback complete transaction.

如何在使用DAO时管理这种交易?

How to manage this sort of transaction while using DAOs?

推荐答案

如果您使用的是普通JDBC,那么您可以在DAO类的两个实例中共享相同的 Connection 实例。

If you are using plain JDBC, what you could do is share the same instance of Connection in the two instances of the DAO classes.

public class EmployeeDAO {

    private Connection conn;

    public void setConnection(Connection conn) {
        this.conn = conn;
    }

    ...
}

public class BankDAO {

    private Connection conn;

    public void setConnection(Connection conn) {
        this.conn = conn;
    }

    ...
}

在客户端代码中,首先需要创建一个 Connection 对象实例。接下来,您需要使用 conn.setAutoCommit(false); 启动事务。将 Connection 对象实例传递给两个DAO类。如果在任何操作中都没有发生错误, conn.commit(); ,否则, conn.rollback();

In the client code, first you need to create a Connection object instance. Next, you need start the transaction, with conn.setAutoCommit(false);. Pass the Connection object instance to the both DAO classes. If no errors occurs in any operation, conn.commit();, otherwise, conn.rollback();

例如:

Connection conn = null;
try {
    // getConnection from pool

    conn.setAutoCommit(false);

    EmployeeDAO employeeDAO = new EmployeeDAO();
    employeeDAO.setConnection(conn);

    BankDAO bankDAO = new BankDAO();
    bankDAO.setConnection(conn);

    // save employee

    // save bank details

    conn.commit();

catch(Exception e) {
    if (conn != null) {
        conn.rollback();
    }
} finally {
    if (conn != null) {
        conn.close();
    }
}

这篇关于使用DAO进行事务管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆