Pregunta

Service facades are usually implemented as stateless session beans, which means that any entities they possibly return will be detached immediately. This makes me think that any entity returned as a result of a service facade business method should eagerly fetch all of its internals, as in the absence of eager fetching, its internals cannot be accessed by service clients. I want to know whether I'm right on this and whether there is possibly any other way which may be more appropriate in certain circumstances.

Thank you

¿Fue útil?

Solución

Yes you're substantially right, entities are detached as soon as they are returned from the session bean method in which they were created or fetched from the database. This means that there is no way, in the client tier, to access lazily loaded related entities. From my job experience I can say that there are two common scenarios. The first in which the data model in the business tier, implemented with entities and enterprise beans, is completely different from the data model used in the client tier; in this case the best solution is to create so called DTOs (data transfer objects), i.e. plain java objects with get and set methods, and use them for transferring data between the two layers. The major drawback of this approach is that writing DTOs could be a long, boring and error prone task and moreover the fact that either they implement no business logic, being pure beans, or the logic must be duplicated in both tiers. This is especially true if the data model in the two tiers is the same and one would reuse behaviour. This leads us to the second approach which consists in building a unique data model with entities to be shared in business and client tier, with the obvious advantage of less code writing and logic reuse. However in order to pass the detached entities from one layer to the other you have only two choices: either declare all your relationships as eager, at risk loading too many objects in memory especially if your entities are strongly interconnected, or leave them lazy and write your facade methods carefully in order to load all the needed fields before returning. I've recently faced a real world project in which the graph of entities connections is almost a complete one, which drove us to prefer lazy loading of relationships, and to avoid writing too many lines of code just to fill the needed related entities of each returned entity in the service facade methods, we resort to DTOs, modelling one of them for each class of client use case and using generic methods to automatically convert entities to the corresponding DTO.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top