M.Wojtaczka
M.Wojtaczka

Reputation: 11

session.save() reflect without transaction commit

Got some bunch of code:

Session session = sessionFactory.openSession();
    Transaction tx = session.getTransaction();

    try
    {
        tx.begin();

        Person person = Person.builder().name("JAN").surname("NOWAK").age(30).build();
        session.save(person);

        tx.commit();
    }

While debugging i see that person is reflected in data base before transaction commit. I set explicitly

<property name="hibernate.connection.autocommit">false</property>

and tried with various hibernate versions but still get the issue.

Even if i throw Exception before commit

try
    {
        tx.begin();

        Person person = Person.builder().name("JAN").surname("NOWAK").age(30).build();
        session.save(person);

        String s = null;
        if (s == null) {
            throw new Exception();
        }

        tx.commit();
    }

Result is the same, Person is added to DB whether I use tx.commit() or NOT.

EDIT:

After changing entity generating strategy from IDENTITY to AUTO it works as I anticipated before, changes in DB are made after commit. Result:

Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
sout: tx.commit()
Hibernate: insert into Person (age, name, surname, id) values (?, ?, ?, ?)

But could anyone explain why so?

Upvotes: 0

Views: 2168

Answers (1)

Jayesh Choudhary
Jayesh Choudhary

Reputation: 798

If you are using save() then you don't need to use tx.commit(), because save() is responsible for returning identifier when called. Therefore you commit or not its value is stored in db immidiately. On the other hand if you want to use commit() then go for persist(). This will explain you in detail Here

Upvotes: 1

Related Questions