JPA刷新期间发生错误-在级联持久性时遇到的处于生命周期状态的非托管对象处于非托管状态

时间:2018-11-16 15:18:58

标签: java osgi entitymanager openjpa aries

我在OSGI平台和Apache Aries JPA 2.6.1上使用Open JPA 2.4.2 我的DAO是使用Apache Aries Blueprint注入的。

blueprint.xml

<blueprint default-activation="lazy"
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v2.0.0" xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0"
xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs" xmlns:cxf="http://cxf.apache.org/blueprint/core">

<jpa:enable />

<bean id="appDAO"
class="com.test.MyDAOImpl">
    <tx:transaction method="*" value="Required" />
</bean>
</blueprint>

MyDAOImpl使用注解注入了EntityManager

public class MyDAOImpl implements MyDAO {

@PersistentContext(unitName = "test-unit")
private EntityManager entityManager;

public EntityObj getEntityObj(int id) {
    return entityManager.find(EntityObj.class, id);
}

public void saveParentObj(ParentOfEntity parentOfEntity) {
    entityManager.persist(parentOfEntity);
    entityManager.flush();
}
}

MyServiceImpl.java

private MyDAO myDAO;

public void updateEntityObj(int id) {
    ParentOfEntity parent = new ParentOfEntity();
    EntityObj obj = myDAO.getEntityObj(id);
    obj.setValue1("1");
    obj.setValue2("2");
    parent.setChild(obj);
    myDAO.saveParentObj(parent);
}

ParentOfEntity.java

class ParentOfEntity {
    private EntityObj child;
    ...
}

这会引发异常

org.apache.openjpa.persistence.InvalidStateException: Encountered unmanaged 
object "com.test.EntityObj-15389840" in life cycle state  unmanaged while 
cascading persistence via field "com.test.ParentOfEntity.child" during 
flush.  However, this field does not allow cascade persist. You cannot flush 
unmanaged objects or graphs that have persistent associations to unmanaged 
objects.
Suggested actions: a) Set the cascade attribute for this field to 
CascadeType.PERSIST or CascadeType.ALL (JPA annotations) or "persist" or 
"all" (JPA orm.xml), 
b) enable cascade-persist globally, 
c) manually persist the related field value prior to flushing. 
d) if the reference belongs to another context, allow reference to it by 
setting StoreContext.setAllowReferenceToSiblingContext().

如果我再次在MyDAO的saveParentObj方法中获取子对象EntityObj,则该过程将成功完成。但这是不必要的,因为我已经有了EntityObj参考,并且该参考也已更新。

您能建议其他解决方案吗?

0 个答案:

没有答案