1

I am working with Spring Boot + Jersey + JPA/Hibernate to build a RESTful API. The issue I am encountering right now is when I have a relationship in my JPA Entity that is lazy loaded I get a lazy load exception when Jersey goes to serialize the object. My question is what is the best way to avoid this / best practices.

I realize I could just do FetchType.EAGER but that seems like a really really bad idea building a huge object graph that may not be necessary.

I've thought about using the DTO pattern, but that seems like a lot of code duplication, so not sure I want to go down this route unless its the best option.

I could switch to EclipseLink because as I understand it does not suffer from the Lazy load no session issues Hibernate like Hibernate does.

The other option I thought about was to put @JsonIgnore on all lazy loaded properties and make another API endpoint to fetch that property. As an example let's say a Person has many addresses, if the end users wants the addresses they would have to request /person/addresses

What is the best way to handle this issue, and why? At the end of the day this API will interface with an AngularJS application. The application will be a pretty decent size. The database that backs in has 80-90 tables.

1 Answer 1

0

I highly recommend you to go for DTO pattern since you have a large model. The reason for that is only by using DTO pattern you can have clear separation between your domain model and service objects. In other case you will not have a layer/room to manage possible future changes in your domain entities or service requirements and those changes most likely will break your existing services.

4
  • That makes sense, in that case does it make sense for JPA / JPQL to return DTO directly where appropriate, when mixing one more more domain objects?
    – jkratz55
    Commented Oct 4, 2015 at 21:05
  • Actually you should design your DTOs according to your service requirements not to the your domain objects. You should create DTOs in your service layer using your domain objects. At least that is what we are using and happy now.
    – cool
    Commented Oct 4, 2015 at 21:17
  • So it should match the requirements of the UI or RESTful API spec, example UI needs userId, userName, firstName, lastName, roles, address then that is what the DTO should have, even know the it could be spread among 3 different domain objects, User, Role, and Address for example
    – jkratz55
    Commented Oct 4, 2015 at 21:42
  • Yeah that is what we are doing mostly. But of course you should do some optimization like if you always need to send username, firstname and lastname you can have a common userdto to use in your other dtos.
    – cool
    Commented Oct 4, 2015 at 21:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.