Java 在使用hibernate';s session.connection()以运行本机sql
在我的项目中,他们以下面提到的方式使用Hibernate会话,然后在事务中保存实体对象Java 在使用hibernate';s session.connection()以运行本机sql,java,hibernate,jakarta-ee,jdbc,Java,Hibernate,Jakarta Ee,Jdbc,在我的项目中,他们以下面提到的方式使用Hibernate会话,然后在事务中保存实体对象 Session session = HibernateUtil.getCurrentSession(); session.beginTransaction(); Employee employee = new Employee() ; employee.setName("someName") ; employee.setEmailId ("someId") employee.setID (100000)
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();
这条路对吗??是否仍将管理事务的??无法在事务中管理会话中的连接对象
请告诉我使用这种方式是否有任何问题???谢谢是的,这里没有问题 但是,使用
Session.createSQLQuery()
运行本机查询要容易得多:
另请参见:
- 是的,这里没有问题
但是,使用
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();