[英]Spring data repository find method hangs when called from inside a thread
I want to call a find method from a repository and somehow it is blocking the thread and never returns. 我想从存储库中调用find方法,并且它以某种方式阻塞线程,并且永不返回。
We use spring data to create repositories. 我们使用spring数据创建存储库。
I have a test case with this code: 我有一个测试用例代码:
Thread t = new Thread(() -> {
repository.findById(1); // this line blocks the thread
}
t.start();
t.join();
The repository implementation is standard, it works correctly when called from the main thread. 存储库实现是标准的,从主线程调用时可以正常工作。
I noticed that spring uses a thread local that contains the current open session. 我注意到spring使用包含当前打开会话的本地线程。 So I tried to bind a new session in the new thread with this code:
因此,我尝试使用以下代码将新会话绑定到新线程中:
EntityManager em = entityManagerFactory.createEntityManager();
EntityManagerHolder emHolder = new EntityManagerHolder(em);
TransactionSynchronizationManager.bindResource(entityManagerFactory, emHolder);
But it didn't work, the repository call still blocks. 但这没有用,存储库调用仍然阻塞。
So I tried to use the newly created EntityManager to find a record from the database using the TransactionTemplate like so: 因此,我尝试使用新创建的EntityManager通过TransactionTemplate从数据库中查找记录,如下所示:
TransactionTemplate template = new TransactionTemplate(transactionManager);
template.execute((TransactionCallback<Object>) status ->
emHolder.getEntityManager().find(User.class, updated.getId()));
But it did't work either, the find method blocks the thread as well. 但这也不起作用,find方法也会阻塞线程。
Do you know what a may be doing wrong? 您知道a可能做错了什么吗? Or is it a bug?
还是一个错误?
I found the problem. 我发现了问题。
We were using hsqldb as embedded database in tests and that was the problem. 我们在测试中使用hsqldb作为嵌入式数据库,这就是问题所在。
It hangs when we try to run a select query from a thread. 当我们尝试从线程运行选择查询时,它挂起。 I think it can't handle multiple connections properly, but I didn't go deep into that.
我认为它不能正确处理多个连接,但是我没有对此进行深入研究。
I just changed the database to h2 and it worked. 我只是将数据库更改为h2而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.