【问题标题】:session.save() reflect without transaction commitsession.save() 反映没有事务提交
【发布时间】:2018-06-09 21:44:58
【问题描述】:

得到了一些代码:

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

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

编辑:

在将实体生成策略从 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 (?, ?, ?, ?)

但谁能解释为什么会这样?

【问题讨论】:

  • 除非您调用 tx.commit,否则您的更改不会被永久存储,但您仍会在事务中看到它们(这通常是数据库事务的工作方式)跨度>
  • 但是即使没有 tx.commit() 或者当我在提交数据之前抛出异常时仍然在 DB 中发生。
  • 这将消除您的疑问,stackoverflow.com/questions/14622962/…
  • 相反,我的问题是:无论我使用 tx.commit 还是 NOT 结果都是一样的。我写给 DB 的人。

标签: java hibernate transactions


【解决方案1】:

如果你使用 save() 那么你不需要使用 tx.commit(),因为 save() 负责在调用时返回标识符。因此,无论您是否提交,它的值都会立即存储在 db 中。另一方面,如果您想使用 commit(),请使用 persist()。这里会为你详细讲解Here

【讨论】:

  • 不幸的是,仍然会导致 insert,但是当我将实体生成策略从 IDENTITY 更改为 SEQUENCE 或 AUTO 时,它会起作用。 DB 在 tx.commit() 之后发生变化。
  • 如果我们从不提交并且事务超时会发生什么?
  • 在什么情况下?保存()或持久()。
  • @JayeshChoudhary 两者
猜你喜欢
  • 1970-01-01
  • 2013-04-22
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 2011-03-30
相关资源
最近更新 更多