0

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?

  • 1
    Your changes aren't going to be stored permanently unless you call *tx.commit* but you will still see them inside the transaction (that's usually how DB transactions work) – dsp_user Dec 29 '17 at 12:57
  • But even without tx.commit() or when i throw Exception before commit data still occurs in DB. – M.Wojtaczka Dec 29 '17 at 13:12
  • This will clear your doubt, https://stackoverflow.com/questions/14622962/what-is-transaction-commit-in-hibernate – Arvind Katte Dec 29 '17 at 13:20
  • Contrary, my issue is: **whether I use tx.commit or NOT result is the same**. Person i written to DB. – M.Wojtaczka Dec 29 '17 at 14:03

1 Answers1

1

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

Jayesh Choudhary
  • 748
  • 2
  • 12
  • 30