Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在使用hibernate';s session.connection()以运行本机sql_Java_Hibernate_Jakarta Ee_Jdbc - Fatal编程技术网

Java 在使用hibernate';s session.connection()以运行本机sql

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)

在我的项目中,他们以下面提到的方式使用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();
这条路对吗??是否仍将管理事务的??无法在事务中管理会话中的连接对象


请告诉我使用这种方式是否有任何问题???谢谢

是的,这里没有问题

但是,使用
Session.createSQLQuery()
运行本机查询要容易得多:

另请参见:


    • 是的,这里没有问题

      但是,使用
      Session.createSQLQuery()
      运行本机查询要容易得多:

      另请参见:


      我认为这个问题也更适合添加我的问题Mukul我认为这个问题也更适合添加我的问题Mukul
      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();