并行运行多个JPA事务 [英] Running multiple JPA transactions in parallel

查看:166
本文介绍了并行运行多个JPA事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个(或更多)Java线程使用JPA从mysql数据库创建,更新和删除实体。为了实现这一点,我有一个PersistenceLayer类创建EntityManager,并为我的所有实体提供保存,更新和删除方法:

I have two (or more) Java Threads creating, updating and deleting entities from a mysql database using JPA. To achieve this I have a PersistenceLayer class creating the EntityManager and providing save, update and delete methods for all my entities looking like:

public void saveEntity(Entity entity) {
    manager.getTransaction().begin();
    manager.persist(entity);
    manager.getTransaction().commit();
}

public void saveEntity2(Entity2 entity) {
    manager.getTransaction().begin();
    manager.persist(entity);
    manager.getTransaction().commit();
}

如果一个线程同时进入操作saveEntity和另一个saveEntity2,将尝试从EntityManager获取事务将失败。然而,我一直认为底层数据库能够管理多个事务,特别是如果两个都在不同的行或甚至不同的表。当然,我可以同步块,但这意味着只有一个数据库连接在一个时间是不可能扩展到多个用户创建多个线程。

If one thread enters operation saveEntity and the other saveEntity2 at the same time, both will try to get the transaction from the EntityManager wich will fail. However I always thought that the underlying database is able to manage multiple transactions, especially if both are working on different rows or even different tables. Of course I could synchronize the blocks, but that would mean only one DB connection is possible at a time which will not scale to multiple users creating several threads.

错误的假设我在这里做吗?是否可以通过JPA向数据库提交多个事务,并让数据库处理并发问题?

What wrong assumption am I doing here? Is it possible to submit multiple transactions to a database via JPA and let the DB handle concurrency issues?

推荐答案

EntityManager 不适用于多个线程。您需要为每个线程获取 EntityManager 的单独实例。

EntityManager is not intended to be used by multiple threads. You need to obtain separate instances of EntityManager for each thread.

实际上,如果使用EJB或Spring,使用事务范围的 EntityManager ,它可以从多个线程使用(它是一个代理,将实际工作委托给单独的线程绑定实例 EntityManager ),但我认为这不是你的情况。

Actually, if you use EJB or Spring you can use a transaction-scoped EntityManager, which can be used from multiple threads (it's a proxy which delegates actual work to separate thread-bound instances of EntityManager), but I think it's not your case.

这篇关于并行运行多个JPA事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆