首页 > 解决方案 > 混合 Hibernate 和原始 JDBC 事务

问题描述

我有一些模型对象是 Hibernate 实体,而另一些则不能(因为我不拥有代码)。我需要跨越两个对象更新的事务。基本上,我想这样做:

Transaction txn = sessionFactory.getCurrentSession().beginTransaction();
fooDao.update(...); // Hibernate-based DAO

// (Apparently the way to get the JDBC Connection.)
Connection con = sessionFactory.
    getSessionFactoryOptions().getServiceRegistry().
    getService(ConnectionProvider.class).getConnection();

try (var ps = con.prepareStatement(...)) {
    ps.setString(...);
    ps.executeUpdate();
}

txn.commit();

在 JDBC 中,启动事务无非是在连接上设置 autoCommit=false (AFAICT)。我不知道 Hibernate 究竟做了什么来启动事务。像这样混合两种更新会有什么问题吗?

标签: hibernatejpajdbc

解决方案


推荐阅读