session.save() reflect without transaction commit

生来就可爱ヽ(ⅴ<●) 提交于 2020-04-17 22:45:16

问题


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:


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



来源:https://stackoverflow.com/questions/48022802/session-save-reflect-without-transaction-commit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!