session.save()反映没有事务提交

问题描述 投票:0回答:1

得到了一些代码:

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

在调试时,我发现在事务提交之前,这个人会反映在数据库中。我明确地设定了

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

并尝试了各种hibernate版本,但仍然遇到问题。

即使我在提交之前抛出异常

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()或NOT,都将Person添加到DB。

编辑:

在将实体生成策略从IDENTITY更改为AUTO之后,它按照我之前的预期工作,在提交后进行DB的更改。结果:

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

但有人可以解释为什么这样吗?

java hibernate transactions
1个回答
0
投票

如果使用save(),则不需要使用tx.commit(),因为save()负责在调用时返回标识符。因此,您提交或不将其值存储在db immidiately中。另一方面,如果你想使用commit(),那么去persist()。这将详细解释你Here

© www.soinside.com 2019 - 2024. All rights reserved.