1

在我的项目中,他们以下面提到的方式使用 Hibernate 的会话,然后将实体对象保存在事务中。

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();

这是正确的方法吗??交易是否仍会被管理??无法将会话中的连接对象管理到事务中????

请问这种方式使用有没有问题???谢谢

4

1 回答 1

6

是的,这里没有问题。

但是,使用以下命令运行本机查询会容易得多Session.createSQLQuery()

Session session = HibernateUtil.getCurrentSession(); 
session.beginTransaction(); 

String name = (String) session
    .createSQLQuery("select name from master_employee where id = ?")
    .setInteger(1, id)
    .uniqueResult();

session.getTransaction().commit();

也可以看看:

于 2012-10-19T07:37:20.390 回答