Rob Micah wrote:I've seen comments in several places that returning JPA entity classes out of an EJB is a bad idea and I can certainly understand why.
Can you show us some sources? Because I don't agree completely. I don't see a problem in returning JPA entities from specific EJBs, as long as you keep their transactional behaviour in mind. As long as the entity is part of the transaction it was retrieved / created with, any changes to the entity will be saved. As soon as the transaction ends, the entity is automatically detached. The latter means that you cannot access any properties that have not yet been (fully) loaded, like linked entities.
I'm curious what design patterns people here are using to avoid this. I've been using an interface that defines getter methods on the fields of the entity class and using the return type of my EJB methods to this interface. Is there a better way to do this?
The interface still has some of the same issues, like unloaded properties not being accessible. What we usually do where I work is create a matching DTO class and convert the entity to an instance of the DTO class. That can be cumbersome though, especially if your entities have many properties.