Is there a way to expose Hibernate Entities as RES

2020-02-11 05:06发布

I am developing a simple webapp which exposes the domain model as RESTful resources. I am planning to use JPA2(Hibernate) with SpringMVC REST support.

While marshalling Hibernate entities into XML/JSON, if the entity is detached it will throw LazyLoadingException for lazy child associations. If the entity is still attached to Hibernate Session it will almost load whole database.

I have tried using Dozer CustomFieldMapper to determine if the property is lazy Hibernate Collection which is not loaded then return NULL.

But if we have bi-directional associations Hibernate eagerly load Many-to-One side and Dozer will try to copy properties which will end up in infinite loop resulting StackOverflow error.

The only work around that I know to resolve this is using DTOs and copying the required properties only into clean POJOs(DTOs) and marshalling then into XML/JSON. But it is terribly painful for complex domain model to copy properties manually.

Is there any other clean/simpler way to (un)marshall Hibernate entities?

3条回答
再贱就再见
2楼-- · 2020-02-11 05:42

I might sound too conservative but I consider using DTOs still a good idea.

The complexity of your mappings is proportional to the granularity of your resources' API, in other words the coarser the more complex.

查看更多
够拽才男人
3楼-- · 2020-02-11 05:46

Take a loot at this class: https://github.com/viniciuspires/reqlist/blob/master/src/main/java/org/reqlist/arch/HibernateAwareObjectMapper.java

I'm using Jackson as a JSON serializer/deserializer, and I had to make this class and add the Hibernate4Module for it to verify if Hibernate.isInitialized and don't accidentaly initialize the property.

After that you just have 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

That worked like a charm for me.

查看更多
我想做一个坏孩纸
4楼-- · 2020-02-11 05:51

I have had an analogous problem with passing Hibernate'd VO's back and forth in GWT applications, and in some projects used Dozer to good effect, and in other projects used the approach described in this article, which basically null's the hibernate proxies before marshalling.

Hope that helps you,

查看更多
登录 后发表回答