How to force initialize a JPA Hibernate proxy for use in a JSON call

I have a Spring 3 + JPA 2.0 application. In my @Controller I need an initialized object, but I have a proxy, I need to initialize it programmatically. I need functionality similar to org.hibernate.Hibernate.initialize(Object) .

Can someone help. The object is used for AJAX operations. If the properties are proxies, I cannot send them as JSON

+8
java spring hibernate jpa
source share
3 answers

No JPA option as far as I know. You should use Hibernate.initialize(..) .

In fact, when I looked at the implementation of sleep mode, lazy collections were apparently initialized in many cases, which was not expected. Like entityManager.contains(..) and Persistence.getPersistenceUtil().isLoaded(...) . Try it, but I don’t think you should rely on such implementation details.

+4
source share

We are doing a similar thing in our application, and we found it useful to separate database entity objects and have another class group for JSON output.

If you use a JSON framework that simply checks your object and pulls out some JSON for each property of the object, then it can have objects such as:

PersonEntity - a class controlled by JPA and also PersonJsonOutput - a class specifically designed for JSON output

In the long run, it can be safer. This allows you to have database changes that are not automatically reflected in your JSON service, you might want to change your JSON service, perhaps instead of breaking old versions as soon as your database object changes.

It also gives you more control over your JSON output in terms of date formats or forcing numbers in the database as strings in your JSON, etc.

This answer really depends on how you create your JSON, but it looks like your library is doing some introspection.

0
source share

I know it's late and the answer is accepted, but another standard JPA way is to call the size () method on the list that you want to initialize before the object returns from the DAO:

 Object.getList().size(); 

This eliminates the need to cheat and use the initialization mechanism to implement

0
source share

Source: https://habr.com/ru/post/651003/


All Articles