Considering the save() method, please refer the code snippet below.
I. I inserted some data in the DB with empId = 1 and then get this object in emp1 in session instance ssn1. Now, I called ssn1.save(emp1) but it doesn't save the object again into the db nor is any exception thrown. Now, if I open a new session, and then call ssn2.save(emp1), it inserts a new record into the db. Why it is behaving in this manner?
II. Also, I if I call saveOrUpdate(emp1) method on ssn2, then it doesn't insert a new record. Please explain this behavior.
Code:
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author vaibhav_garg01
*/
public class SessionTest {
public static void main(String args[]){
try{
Configuration cfg = new Configuration().configure();
SessionFactory sf = cfg.buildSessionFactory();
Session ssn1 = sf.openSession();
ssn1.beginTransaction();
Emp emp1 = new Emp("Emp1", 12, 1112);
emp1 = (Emp) ssn1.get(Emp.class, 1);
if(emp1 != null) emp1.setEmpAge(3);
//It doesn't save the emp1 to the DB associated with ssn1
ssn1.save(emp1);
ssn1.flush();
ssn1.getTransaction().commit();
ssn1.close();
Session ssn2 = sf.openSession();
ssn2.beginTransaction();
//It saves the emp1 to the DB associated with ssn2
ssn2.save(emp1);
//It doesn't save a new record, rather, it updates the same record
ssn2.saveOrUpdate(emp1);
ssn2.getTransaction().commit();
ssn2.close();
}
catch(Exception e){
System.out.println("Exception is : " + e);
e.printStackTrace();
}
}
}