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

在调试时,我看到该人反映在事务提交之前的数据库中。我明确设置

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

并尝试使用各种休眠版本,但仍然遇到问题。

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

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 都会添加到数据库中。

编辑:

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

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((。这将在这里详细解释你

最新更新