想要立即将数据保存到数据库中的表中 [英] Want to save data into table in database immediately
问题描述
使用Spring Data JPA存储库将数据保存到数据库时,我遇到了一个问题.
I'm facing an issue with saving data to database using a Spring Data JPA repository.
我的情况:我正在使用一个循环来逐一收集和保存数据.收集所有数据需要花费大量时间.因此,我想将每个记录的数据立即保存到表的数据库中.我正在使用saveAndFlush
方法,但是数据没有立即保存到表中.
My scenario: I'm using a loop to collect and save data one by one. It takes a lot of time to collect all the data. Therefore I want to save the data for each record immediately into table into the database. I'm using saveAndFlush
method but the data is not being saved into the table immediately.
我等不及要收集所有数据,因为可能要花一整天才能收集所有数据.
I cannot wait until all the data is collected because it maybe take a full day to collect all.
推荐答案
我不确定100%确定如何测试数据是否不会立即写入数据库,但是我猜您正在使用单独的数据库进行检查连接.
I'm not 100% sure how you test that the data is not written immediately to the database, but I'm guessing you are checking with a separate database connection.
这可能意味着您的数据实际上已写入数据库,但未提交,因此对于其他会话不可见.
This probably means that your data in deed is written to the database, but not committed and therefore not visible for other sessions.
确保事务范围仅在用于编写的循环内 .
Make sure that the transaction scope is only inside the loop you are using for writing.
为此,当对save
的调用在事务内时,包含for循环的方法不应具有@Transactional
批注或事务中包含的任何其他方式. saveAndFlush
不是必需的,因为事务将提交,并且无论如何都会触发刷新.
For this the method containing the for loop should not have a @Transactional
annotation or in any other way included in a transaction, while the call to save
is within a transaction. saveAndFlush
is not necessary since the transaction commits and this will trigger a flush anyway.
如果对save
的调用是与数据库的唯一交互,Spring实际上会自动将其包装在事务中,因为存储库开箱即用@Transactional
进行了注释.否则,您需要使用 Spring的交易支持来实现这一目标.
If the call to save
the only interaction with the database Spring will actually automatically wrap it in a transaction, because repositories are annotated with @Transactional
out of the box. Otherwise you'll need to use the transaction support of Spring to achieve this.
这篇关于想要立即将数据保存到数据库中的表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!