Is there a way to open Hibernate objects as RESTful resources without a DTO?

I am developing a simple webapp that provides a domain model as RESTful resources. I plan to use JPA2 (Hibernate) with support for SpringMVC REST.

When sorting Hibernate objects in XML / JSON, if the object is detached, it will throw a LazyLoadingException for lazy child associations. If the object is still connected to the Hibernate session, it will almost load the entire database.

I tried using Dozer CustomFieldMapper to determine if a property is a lazy Hibernate Collection that is not loaded, and then returns NULL.

But if we have bi-directional associations, Hibernate eagerly loads the Many-to-strong> One side, and Dozer tries to copy properties that will ultimately be caused by a StackOverflow error in the final loop.

The only work I know to solve this problem is to use DTO and copy the necessary properties only into pure POJOs (DTOs) and then convert to XML / JSON. But for a complex domain model, it is very difficult to copy properties manually.

Is there any other clean / simpler way to (un) sort Hibernate objects?

+6
source share
3 answers

I had a similar problem with passing Hibernate'd VO back and forth in GWT applications, and some projects used Dozer for a good effect, and other projects used the approach described in this article , in which mostly zero-hibernate proxies before sorting.

Hope this helps,

+3
source

I may seem too conservative, but I think using DTO is still a good idea.

The complexity of your comparisons is proportional to the granularity of the API of your resources, in other words, the more difficult task.

+4
source

Take prey in this class: https://github.com/viniciuspires/reqlist/blob/master/src/main/java/org/reqlist/arch/HibernateAwareObjectMapper.java

I use Jackson as a JSON serializer / deserializer, and I had to make this class and add a Hibernate4Module to check if Hibernate.isInitialized and not accidentally initialize the property.

After that, you just need to configure it as your ObjectMapper and pass it to the MessageConverters array, as I did in this line:

https://github.com/viniciuspires/reqlist/blob/master/src/main/resources/META-INF/org.reqlist.context.xml#L21

It worked like a charm for me.

+2
source

All Articles