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

前端 未结 6 703
孤独总比滥情好
孤独总比滥情好 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:07

    save() returns an identifier, and if an INSERT has to be executed to get the identifier, this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is not good in a long-running conversation with an extended Session/persistence context.

    persist() is used on transient objects. It makes a transient instance persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.It also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.

    0 讨论(0)
  • 2020-12-03 06:09
    • Return type: both functions INSERT the records into a database, but return type of persist() method is void while return type of save() method is that primary key id value which is generated by hibernate.

    • Identifier : persist() method doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.

    • Transaction boundaries: We can invoke persist() method inside transaction only, so it’s safe and takes care of any cascaded objects. save() method can invoke inside or outside of a transaction.

    • Context : persist() methods adds the entity object to persistent context and track any further changes. Any further changes are saved at the time of committing transaction, like persist.

    finally persist() method is better than save().

    examples

    0 讨论(0)
  • 2020-12-03 06:09

    Persist():

    • It is a void method and does not guarantee that identifier value is assigned to persistence instance after INSERT. the assignment might happen at flush time.
    • It will not be executed if its called from outside transactions boundaries.
    • It will be useful for long-running conversations with extended session/persistence context.

    Save():

    • It will return the identifier after executing INSERT.
    • It will be executed even outside transaction boundary.
    • It is not useful for long-running conversations.
    0 讨论(0)
  • 2020-12-03 06:15

    The save() method do insert statement normally outsite transaction

    public class HibernateSaveExample {
    
        public static void main(String[] args) {
    
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
            Session session = sessionFactory.openSession();
            Student student = new Student("javabycode.com", new Date(), "USA", "1234569");
            Long studentId = (Long) session.save(student);
            System.out.println(" Identifier : " + studentId);
            System.out.println(" Successfully saved");
    
            Session session2 = sessionFactory.openSession();
            Transaction trans = session2.beginTransaction();
    
            Student student2 = new Student("javabycode.com", new Date(), "USA", "1234569");
            Long studentId2 = (Long) session2.save(student2);
            trans.commit();
            System.out.println(" Identifier : " + studentId2);
            System.out.println(" Successfully saved");
    
            sessionFactory.close();
        }
    
    }
    

    and the persist() method can't do it.

    And one more difference between save and persist method in Hibernate: persist is supported by JPA, while save is only supported by Hibernate.

    From the tutorial Difference between save and persist method in Hibernate

    0 讨论(0)
  • 2020-12-03 06:26

    I did some mock testing to record the difference between Save() and Persist().

    Sounds like both these methods behaves same when dealing with Transient Entity but differ when dealing with Detached Entity.

    For the below example , take EmployeeVehicle as an Entity with PK as vehicleId which is a generated value and vehicleName as one of its property .

    Example 1 : Dealing with Transient Object

                     Session session = factory.openSession();
                     session.beginTransaction();
                     EmployeeVehicle entity = new EmployeeVehicle();
                        entity.setVehicleName("Honda");
                     session.save(entity);
                     // session.persist(entity);
                    session.getTransaction().commit();
                    session.close();
    

    Result : select nextval ('hibernate_sequence') // This is for vehicle Id generated : 36

    insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Honda, 36)
    
    Repeat the same with using persist(entity) and will result the same with new Id ( say 37 , honda ) ;
    

    Example 2 : Dealing with Detached Object

    // Session 1 
                // Get the previously saved Vehicle Entity 
               Session session = factory.openSession();
                session.beginTransaction();
                EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
               session.close();
    
               // Session 2
               // Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it 
             (i) Using Save() to persist a detached object 
               Session session2 = factory.openSession();
                session2.beginTransaction();
                        entity.setVehicleName("Toyota");
                session2.save(entity);
                session2.getTransaction().commit();
                session2.close();
    

    Result : You might be expecting the Vehicle with id : 36 obtained in previous session is updated with name as "Toyota" . But what happens is that a new entity is saved in the DB with new Id generated for and Name as "Toyota"

             select nextval ('hibernate_sequence')
             insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Toyota, 39)
    
             (ii) Using Persist()  to persist a detached object 
    
                // Session 1 
                Session session = factory.openSession();
        session.beginTransaction();
        EmployeeVehicle entity = EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
        session.close();
    

    // Session 2 // Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it (i) Using persist() to persist a detached object

                Session session2 = factory.openSession();
        session2.beginTransaction();
                entity.setVehicleName("Toyota");
        session2.persist(entity);
        session2.getTransaction().commit();
        session2.close();
    

    Result : Exception being thrown : detached entity passed to persist

    So, it is always better to use Persist() rather than Save() as save has to be carefully used when dealing with session and transcation .

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题