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

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

提交回复
热议问题