SpringBoottest:可以从新线程访问JPA存储库
我有一个在主线程中工作的自动装配的 jpa 存储库对象。我可以读取和写入它,在日志消息中查看它。但是,我需要从新线程使用存储库。将其传递给另一个线程后,它失败并出现错误:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "my_schema.my_table" does not exist
主线程中的相同存储库没有问题。
import static org.awaitility.Awaitility.await;
@Autowired
MyRepository repository;
@Test
@Sql(scripts = "/database/init.sql",
config = @SqlConfig(dataSource = "myDataSource",
transactionManager = "myTransactionManager"))
@Transactional(transactionManager = "myTransactionManager",
rollbackFor = Exception.class,
propagation = Propagation.REQUIRES_NEW)
public void test() {
repository.saveAndFlush(new TestObject("test"));
log.info(repository.findAll().toString())
await().atMost(TIMEOUT, SECONDS).until(() -> correctionRepository.findAll().size() == 1);
}
在这个例子中我使用了 Awaitility 类,但这并不重要。如果我向 Kafka 监听器发送一些消息,也会出现同样的情况。
如何跨多个线程使用存储库?
I have an autowired jpa repository object working in main thread. I can read to and write from it, see it in log message. However, I need to use repository from a new thread. After passing it to another thread, it fails with error:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "my_schema.my_table" does not exist
There are no problems with same repository in main thread.
import static org.awaitility.Awaitility.await;
@Autowired
MyRepository repository;
@Test
@Sql(scripts = "/database/init.sql",
config = @SqlConfig(dataSource = "myDataSource",
transactionManager = "myTransactionManager"))
@Transactional(transactionManager = "myTransactionManager",
rollbackFor = Exception.class,
propagation = Propagation.REQUIRES_NEW)
public void test() {
repository.saveAndFlush(new TestObject("test"));
log.info(repository.findAll().toString())
await().atMost(TIMEOUT, SECONDS).until(() -> correctionRepository.findAll().size() == 1);
}
In this example I use Awaitility class, but it doesn't matter. The same situation if I sending some message to a Kafka listener.
How can I use the repository across multiple threads ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论