Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 750
pmanolov Avatar asked Jan 12 '11 23:01

pmanolov


People also ask

Could not initialize proxy the owning session was closed hibernate?

We have seen that this error mainly comes when you have closed the connection and trying to access the proxy object which is no fully initialized. Since Proxy object needs a connection, you can either reattach object to the session or carefully avoid writing such code, which access uninitialized Proxy object.

Which method returns proxy object in hibernate?

Explanation: load() method returns proxy object. load() method should be used if it is sure that instance exists.

How does Hibernate proxy work?

By definition, a proxy is “a function authorized to act as the deputy or substitute for another”. This applies to Hibernate when we call Session. load() to create what is called an uninitialized proxy of our desired entity class. This subclass will be the one to be returned instead of querying the database directly.


2 Answers

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.

like image 79
Bozho Avatar answered Oct 25 '22 21:10

Bozho


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.

like image 45
Kieran Avatar answered Oct 25 '22 19:10

Kieran