【问题标题】:Any problems in using hibernate's session.connection() to run native sql使用 hibernate 的 session.connection() 运行原生 sql 的任何问题
【发布时间】: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();

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

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

【问题讨论】:

标签: java hibernate jakarta-ee jdbc


【解决方案1】:

是的,这里没有问题。

但是,使用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();

另请参阅:

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 2011-06-23
    • 2011-04-01
    • 2021-07-21
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    相关资源
    最近更新 更多