简体   繁体   English

在 Spring Boot 应用程序的 @Transactional 方法中调用 flush()

[英]Calling flush() in @Transactional method in Spring Boot application

Is it possible that calling Hibernate flush() in the middle of @Transactional method will save incomplete results in the database?在@Transactional 方法中间调用Hibernate flush() 是否有可能将不完整的结果保存在数据库中? For example, is it possible that this function could save "John" to the database?例如,这个函数是否有可能将“John”保存到数据库中?

@Transactional
public void tt() {
    Student s = new Student("John");
    em.persist(s);
    em.flush();
    // Perform some calculations that change some attributes of the instance
    s.setName("Jeff");
}

I tried it with H2 in-memory database and it didn't save incomplete transaction changes.我用 H2 内存数据库尝试过它,它没有保存不完整的事务更改。 But is it possible under certain conditions and maybe with another DB engine?但是在某些条件下是否可能并且可能使用另一个数据库引擎?

It should not save anything before you call em.commit() or transaction ends.在您调用em.commit()或事务结束之前,它不应该保存任何内容。 The best explanation I found is from here .Below the essential excerpt:我找到的最好的解释来自这里。下面是重要的摘录:

This operation will cause DML statements (insert/update/delete etc) to be executed to the database but the current transaction will not be committed.此操作将导致对数据库执行 DML 语句(插入/更新/删除等),但不会提交当前事务。 That means flush() will not make current changes visible to other EntityManager instances or other external database clients;这意味着 flush() 不会使当前更改对其他 EntityManager 实例或其他外部数据库客户端可见; that will only happen at the transaction commit.这只会在事务提交时发生。 In other words flush() operation will only flush the current memory cache from EntityManager to the database session.换句话说,flush() 操作只会将当前内存缓存从 EntityManager 刷新到数据库会话。

So the flush might raise some JPA exceptions but it would not actually be committed to database before transaction ends.所以刷新可能会引发一些 JPA 异常,但它实际上不会在事务结束之前提交到数据库。

Related question: JPA flush vs commit相关问题: JPA 刷新 vs 提交

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM