java-OpenJPA事务-单个或多个实体管理器?
作者:互联网
我有一个DBManager单例,可确保实例化单个EntityManagerFactory.我正在讨论使用单个或多个EntityManager的问题,因为只有单个事务与EntityManager相关联.
我需要使用多个交易. JPA不支持嵌套事务.
所以我的问题是:在大多数在单个数据库环境中使用事务的普通应用程序中,您是否完全使用单个EntityManager?到目前为止,我一直在使用多个EntityManager,但是想看看创建单个EntityManager是否可以达到目的,并且还可以加快速度.
因此,我发现以下帮助:希望它也能帮助其他人.
http://en.wikibooks.org/wiki/Java_Persistence/Transactions#Nested_Transactions
Technically in JPA the EntityManager is in a transaction from the
point it is created. So begin is somewhat redundant. Until begin is
called, certain operations such as persist, merge, remove cannot be
called. Queries can still be performed, and objects that were queried
can be changed, although this is somewhat unspecified what will happen
to these changes in the JPA spec, normally they will be committed,
however it is best to call begin before making any changes to your
objects. Normally it is best to create a new EntityManager for each
transaction to avoid have stale objects remaining in the persistence
context, and to allow previously managed objects to garbage collect.After a successful commit the EntityManager can continue to be used,
and all of the managed objects remain managed. However it is normally
best to close or clear the EntityManager to allow garbage collection
and avoid stale data. If the commit fails, then the managed objects
are considered detached, and the EntityManager is cleared. This means
that commit failures cannot be caught and retried, if a failure
occurs, the entire transaction must be performed again. The previously
managed object may also be left in an inconsistent state, meaning some
of the objects locking version may have been incremented. Commit will
also fail if the transaction has been marked for rollback. This can
occur either explicitly by calling setRollbackOnly or is required to
be set if any query or find operation fails. This can be an issue, as
some queries may fail, but may not be desired to cause the entire
transaction to be rolled back.The rollback operation will rollback the database transaction only.
The managed objects in the persistence context will become detached
and the EntityManager is cleared. This means any object previously
read, should no longer be used, and is no longer part of the
persistence context. The changes made to the objects will be left as
is, the object changes will not be reverted.
解决方法:
根据定义,EntityManager不是线程安全的.因此,除非您的应用程序是单线程的,否则使用单个EM可能不是可行的方法.
标签:openjpa,jpa,transactions,entitymanager,java 来源: https://codeday.me/bug/20191202/2084903.html