1

I have been making a simple program to save an employee details in mysql using hibernate framework as follows...

public class Manifest {

     Session session;

     public static void main(String[] args) {
         Employee employee = new Employee("varun");
         new Manifest().addEmployee(employee); 
     }

     /* Method to CREATE an employee in the database */
     public void addEmployee(Employee employee){

          Integer employeeID=null;
          SessionGenerator sessionGenerator = new SessionGenerator();
          try{
            session = sessionGenerator.getSessionToDb();
            employeeID = (Integer) session.save(employee);
            System.out.println(employeeId); 
          }catch (HibernateException e) {
                 e.printStackTrace(); 
          }finally {
                 session.close(); 
          } 
     }  
}

I am aware of the fact that I should use session.beginTransaction(); & tx.commit() but my question is that why no exception is thrown here in my case and it is printing employeeId on console but not making any entry in database.. What the reason behind that???

1 Answer 1

1

1) Session.save() may perform an INSERT outside transaction boundaries: save() method returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. "identity" generator), this INSERT happens immediately (in order to get an identity), no matter if you are inside or outside of a transaction.

2) Commit might happen even without transaction if you set:

<property name="connection.autocommit">true</property>

that's why an exception is not raised

Check this article (Working nontransactionally with Hibernate): https://developer.jboss.org/wiki/Non-transactionalDataAccessAndTheAuto-commitMode

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.