I am using Open JPA 2.4.2 on an OSGI platform with Apache Aries JPA 2.6.1 My DAO is injected using 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 has the EntityManager injected using annotations
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;
...
}
This throws an exception
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().
If I fetch the child - EntityObj again in the saveParentObj method of MyDAO, then it goes through successfully. But this is unnecessary since I already have the entityObj reference and which also has been updated.
Can you advise on any other solution for the same?