How to force Initialize a Hibernate JPA proxy to use it in a JSON call
Asked Answered
F

3

8

I have a Spring 3 + JPA 2.0 application. In my @Controller I need an initialized object, but I have proxies , I need to be able 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 it as JSON

Freezing answered 12/1, 2011 at 23:39 Comment(0)
I
4

No JPA option to my knowledge. You should use Hibernate.initialize(..).

In fact, when I took a look at the hibernate implementation, lazy collections appear to be initialized in many cases that one wouldn't expect. Like entityManager.contains(..) and Persistence.getPersistenceUtil().isLoaded(...). Give these a try, but I don't think you should rely on such implementation details.

Intrastate answered 13/1, 2011 at 13:28 Comment(1)
Yes thanks, I though this might have been the case. I didn't want to create additional objects and then send that to the view. Since we are still early in the project we've decided to move to hibernate as the JPA reasons didn't stick :). Now for all hibernate users just use Hibernate.initialise(..)Freezing
L
1

We are doing a similar thing in our application and we have found it useful to split our database entity objects and have another bunch of classes for the JSON output.

If you're using a JSON framework that just inspects your object and chucks out some JSON for each and every property on the object then being able to have objects such as:

PersonEntity - Class managed by JPA and PersonJsonOutput - Class specifically designed for JSON output

Might be safer in the long run. This allows you to have database changes that don't automatically get reflected in your JSON service, you might want to version your JSON service perhaps rather than break old versions as soon as your database entity changes.

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

This answer really just depends on how you're generating your JSON, but it sounds like your library does some introspection.

Loafer answered 24/1, 2011 at 22:31 Comment(0)
C
1

I know it is late and the answer is accepted, but another standard JPA way is to call the size() method on the list you wish to initialize prior to returning the object from the DAO:

Object.getList().size(); 

This saves you having to cheat and use an implementation-specific mechanism for initialization

Conservatism answered 29/6, 2015 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.