原始JDBC,Guice和Transactions

时间:2015-04-14 18:49:59

标签: jdbc guice dao

我尝试创建一个具有多个DAO的服务,目前是AddressDao和CustomerDao,知道我想创建一个跨越这两个的事务,如:

@Inject
private CustomerDao customerDao;

@Inject
private AddressDao addressDao;

Customer getCustomer(int id) {
    Customer customer = customerDao.getCustomer(id);
    customer.setAddress(addressDao.getAddress(customer.getAddressId());
    return customer;
}

在Daos中我的东西看起来像那样

public class CustomerDaoJdbcImpl implements CustomerDao {
    private static final Logger logger = LoggerFactory.getLogger(CustomerDaoJdbcImpl.class);

    @Inject
    private Database db;


    public Customer getCustomer(int id) {
      try(Connection connection = db.getConnection()) {
      } catch(SQLException e) {
       ...
      }
    }
}

现在,由于我的连接被注入了dao,我无法跨越事务。 此外,我认为我做得不对,也许需要一本好书来理解一切。

有哪些首选解决方案?或者我做错了吗?

目前我认为我有一个解决方案,但它缺乏线程。

我收到了一些代码: https://stackoverflow.com/a/2353795/2250209

在这里: https://github.com/mybatis/guice/tree/master/src/main/java/org/mybatis/guice/transactional

目前我有一个数据库类从数据源中提取连接,这个类被注入DAO,如果我注释了DAO或服务,连接将保持打开,直到我调用commit或rollback,但我不知道知道这是否是最佳模式,因为有些人建议关闭方法内的连接。

0 个答案:

没有答案