Java – How to Avoid LazyInitializationException Using Hibernate and Jersey

api-designdesignjavajparest

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.

Best Answer

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.

Related Topic