3
\$\begingroup\$

In my project, they use Hibernate's session the below mentioned way and then save entity objects with in a 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();

Now for few functionality I decided to run native SQL. Below is the way i used to run native sql. I wanted to run the queries with-in a transaction and so i decided to write the code the below way

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

Is this the right way ?? will the transaction's still be managed ?? taking the connection object from session cannot be managed in to the transaction ????

Please tell if there any problems in using this way ??? thanks

asked Oct 19, 2012 at 7:34
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Since Hibernate session provides APIs to run native SQL queries, I would avoid extracting the connection from the session and leave the life cycle management of the Statement, ResultSet used for running native queries, to Hibernate Session itself. There must be some reason why they discourage the use of connection like this, directly and so it is being deprecated.

answered Oct 19, 2012 at 16:20
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.