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
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.
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
精彩评论