Through documentation i can find only one difference that is save method generates returns the object as generated identifier but persist does not.Is it the only purpose for
public class TestSave {
public static void main(String[] args) {
Session session= HibernateUtil.getSessionFactory().openSession();
Person person= (Person) session.get(Person.class, 1);
System.out.println(person.getName());
session.close();
Session session1= HibernateUtil.getSessionFactory().openSession();
session1.beginTransaction();
person.setName("person saved with Persist");
session1.getTransaction().commit();
System.out.println(session1.save(person));
//session1.persist(person);
session1.flush();
session1.close();
}
}
Difference between Save and persist , Save execute outside the Transaction. Execute the above code and check the console System.out.println(session1.save(person)) will return with identifier and execute it again, it will increment your identifier. Now if you try to Save another record in Person table in database with the below code and refresh the databse table and check the id column in database. Its value will be incremented.
public class TestMain {
public static void main(String[] args) {
Person person = new Person();
saveEntity(person);
}
private static void saveEntity(Person person) {
person.setId(1);
person.setName("Concretepage1");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
session.close();
}
If we try to persist data outside transaction boundary it give exception.