The process of using ajax:hibernate Entity => json, Flex remoteobject:hibernate Entity => ActionScript object frequently encounters the following problems:
Problem:
1.Hibernate throws Lazyinitializationexception If session is closed when a deferred-load property access is encountered
In the case of One-to-many in 2.Hibernate, if there is no control in serialization, the entire database may be serialized
3. Excessive use of dto/valueobject to solve this problem.
Solution:
Generates a dynamic proxy for the entity object, blocks the Getxxxx () method, and, if the property is accessed for deferred loading, return null instead of throwing the lazyinitializationexception, recursively generating the property's proxy. Serialization automatically stops whenever a property is encountered that does not delay loading. Avoid serializing the entire entity, causing problems that might serialize the entire database.
Similar solutions:
Hibernateconverter in Dwr, when serialized, a property that encounters a deferred load automatically stops the convert operation. and Hibernatebeanserializer is once and for all, regardless of object => JSON can work.
Use Use cases:
Java code
//role为原始对象
role = (Role)roleDao.getById( new Long( 1 ));
//生成的动态代理proxyRole,访问延迟加载的属性将return null
Role proxyRole = (Role) new HibernateBeanSerializer<Role>(role).getProxy ();
assertNotNull(role.getResource());
assertNull (proxyRole.getResource()); //延迟加载,为null
Hibernate.initialize (role.getResource()); //抓取进来
assertNotNull (proxyRole.getResource()); //不为null
//role为原始对象
role = (Role)roleDao.getById(new Long(1));
//生成的动态代理proxyRole,访问 延迟加载的属性将return null
Role proxyRole = (Role)new HibernateBeanSerializer<Role>(role).getProxy ();
assertNotNull(role.getResource());
assertNull (proxyRole.getResource()); //延迟加载,为null
Hibernate.initialize (role.getResource()); //抓取进来
assertNotNull (proxyRole.getResource()); //不为null