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
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.
Explanation: load() method returns proxy object. load() method should be used if it is sure that instance exists.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With