session.save()反映没有事务提交 [英] session.save() reflect without transaction commit

查看:117
本文介绍了session.save()反映没有事务提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些代码:

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();
    }

结果相同,无论我使用 tx.commit()还是不使用,都会将Person添加到数据库中.

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

在将实体生成策略从 IDENTITY 更改为 AUTO 后,它的工作与我之前预期的一样,提交后对数据库进行了更改.结果:

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 (?, ?, ?, ?)

但是有人能解释为什么吗?

推荐答案

如果使用save(),则无需使用tx.commit(),因为save()负责在调用时返回标识符.因此,您是否提交它的值是否立即存储在db中.另一方面,如果您想使用commit(),那么请使用persist().这将在此处

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

这篇关于session.save()反映没有事务提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆