Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

java - Is there a way to expose Hibernate Entities as RESTful resources without DTOs?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...