We are using EJBs with JPA (using eclipselink) and want to pass our entities between our EJBs so we do not need to do any DTO mapping.
However, the problem we have is that while an entity is attached to the entity manager, a call to a setter method will be persisted to the database. Therefore, some sloppy code in another EJB could accidentally make changes to the database without realising (and without validation of the data).
We can see two solutions:
1) Make the EJB interfaces remote so that the entities are serialized and therefore detached. However, we lose the lazy load capabilities and so need a whole raft of methods for all the different permutations of entity trees.
2) Detach the entities from the entity manager. EclipseLink still gives us lazy load (excellent ), however when the lazy load for a relationship runs the entities on the relationship are attached, even if we have cascade detach specified on the relationship. (which seems like it might be a bug).
So two questions. Is there a way to have lazy load available on a detached entity such that lazy loaded relationship entities are also detached? Is there a better solution to the above issue?
detach() is not a very safe operation, so I would not recommend using it.
Are both EJB's in the same transaction? If they are in different transactions, then everything will become detached and any changes will be ignored.
If they are in the same transaction, then would you not want to persist any changes?
If you were using a non-managed EntityManager you could just create a non-transactional EntityManager for your query, so its objects would never be committed. If you are using JTA and a EJB managed EntityManager this would be difficult.
You could also use copy() on the EclipseLink JpaEntityManager to detach the object to the desired depth.
Perhaps provide both a local and remote interface, and in the EJB's that want detached Entities use the remote one. OR fix your code that is incorrectly changing the Entities.