4
votes

Just a architectural question in Java/Hibernate/Spring/Mysql stack

Should I use OpenSessionInView Pattern or use DTO objects in my service layer, to counter the lazy loading exceptions.

Is it a good practice to return Domain/Entity objects from Service layer? Or is it a good practice to return DTO objects, which are later serialized into xml/json in web service layer.

2

2 Answers

1
votes

I follow a really simple rule:

DTOs is more or less the translation from one domain to another. This means DTOs I use just when I have a physical separation between two layers.

Meaning in the case you have JSPs you can use the OpenSessionInView pattern to avoid a lot of over work translating the models and so on.

0
votes

I would always use a DTO approach because of the unpredictable performance implications of the open session in view anti-pattern.

I created Blaze-Persistence Entity Views for exactly that use case. You essentially define DTOs for JPA entities as interfaces and apply them on a query. It supports mapping nested DTOs, collection etc., essentially everything you'd expect and on top of that, it will improve your query performance as it will generate queries fetching just the data that you actually require for the DTOs.

The entity views for your example could look like this

@EntityView(Person.class)
interface PersonDto {
  String getName();
}

Querying could look like this

List<PersonDto> dtos = entityViewManager.applySetting(
  EntityViewSetting.create(PersonDto.class),
  criteriaBuilderFactory.create(em, Person.class)
).getResultList();