user182944
user182944

Reputation: 8067

Hibernate persist() method

Is the below statement a valid one?

persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries

When I try the below code using persist; then the row is getting inserted without any transaction (It is commented out).

SessionFactory sessionFactory = new Configuration().configure("student.cfg.xml").buildSessionFactory();
    Session session = sessionFactory.openSession();

    //Transaction tran = session.beginTransaction();

    /*
     * Persist is working without transaction boundaries ===> why?
     */

    Student student = new Student();
    student.setFirstName("xxx");
    student.setLastName("yyy");
    student.setCity("zzz");
    student.setState("ppp");
    student.setCountry("@@@");
    student.setId("123456");
            session.persist(student);
            //tran.commit();
            session.flush();
    session.close();

Upvotes: 2

Views: 1617

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200138

persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries

This statement is correct. When control returns from persist() back to your code, no INSERT statements have been executed. These statements are guaranteed to be deferred until session flushing. Note that persist() would be a pointless method if no insert happened ever.

Upvotes: 1

Manoj Kathiriya
Manoj Kathiriya

Reputation: 3416

AFAIK data is saving because of session.flush(), try after removing this, mostly you will get an error.

Hibernate persist

Diff. save & persist

Upvotes: 0

Related Questions