Whats the difference between persist() and save() in Hibernate?

前端 未结 6 730
孤独总比滥情好
孤独总比滥情好 2020-12-03 05:47

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

6条回答
  •  悲哀的现实
    2020-12-03 06:27

    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.

提交回复
热议问题