每当我想保留任何实体时,都会执行以下代码。事情似乎工作正常,但我不明白它是如何工作的!
EntityManager em = getEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
em.persist( ent );
userTransaction.commit();
上面的 EntityManager 是整个应用程序共享的单个实例。开始交易后;我只是说em.persist(entity).. hibernate怎么知道它属于哪个事务!
假设我的应用程序上有 10 个并发用户,并且所有 10 个线程都在执行上述代码。因此,创建并提交了 10 个独立事务。但是所有 10 个不同的实体我都没有将它们与各自的交易相关联;那么JPA是如何解决的!
基于答案;我们有以下;我们是说每个线程都应该有一个 EntityManager 实例吗?这不会是服务器上的杀戮!我们应该汇集这些实例吗?它不等于再次实现某种连接池吗?
最佳答案
它正在使用 ThreadLocal交易的变量。
另请参阅 UserTransaction 的文档。 :
begin()
Create a new transaction and associate it with the current thread.
不过,您不应该共享 EntityManager,因为它不能保证是线程安全的。
但是,如果您将它注入(inject)到 EJB 中,则不必担心线程安全:http://www.adam-bien.com/roller/abien/entry/is_in_an_ejb_injected
如果你使用 Spring 注入(inject)它,你会得到一个线程安全的代理:http://static.springsource.org/spring/docs/3.1.1.RELEASE/spring-framework-reference/html/orm.html#orm-jpa-straight
Although EntityManagerFactory instances are thread-safe, EntityManager instances are not. The injected JPA EntityManager behaves like an EntityManager fetched from an application server's JNDI environment, as defined by the JPA specification. It delegates all calls to the current transactional EntityManager, if any; otherwise, it falls back to a newly created EntityManager per operation, in effect making its usage thread-safe.
关于hibernate - JPA 事务的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11221072/