【发布时间】:2012-10-09 18:37:59
【问题描述】:
在我的项目中,他们以下面提到的方式使用 Hibernate 的会话,然后将实体对象保存在 transaction 中。
Session session = HibernateUtil.getCurrentSession();
session.beginTransaction();
Employee employee = new Employee() ;
employee.setName("someName") ;
employee.setEmailId ("someId")
employee.setID (100000) ;
session.saveOrUpdate(employee) ;
session.getTransaction().commit();
现在我决定运行本机 SQL 的一些功能。下面是我用来运行本机 sql 的方式。我想在事务中运行查询,所以我决定按以下方式编写代码
String query = "select name from master_employee where id=?"
Session session = HibernateUtil.getCurrentSession();
session.beginTransaction();
Connection connection = session.connection();
PreparedStatement psStmt = connection.prepareStatement(query);
psStmt.setInt(1,id) ;
ResultSet resultSet = psStmt.executeQuery();
// here i will take data from this result set
psStmt.close();
resultSet.close() ;
// I am not closing the connection object since am taking it from hibernate session
// rather i commit hibernate's transaction
session.getTransaction().commit();
这是正确的方法吗?交易是否仍会被管理??无法将会话中的连接对象管理到事务中????
请问这种方式使用有没有问题???谢谢
【问题讨论】:
-
我觉得这个问题更适合codereview.stackexchange.com
-
Mukul 也添加了我的问题
标签: java hibernate jakarta-ee jdbc