我在带有 Apache Aries JPA 2.6.1 的 OSGI 平台上使用 Open JPA 2.4.2 我的 DAO 是使用 Apache Aries 蓝图注入的。
蓝图.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 引用并且它也已更新。
您能否就任何其他解决方案提出建议?