Using dynamic proxies to resolve hibernate serialization to avoid delay loading problems

Source: Internet
Author: User
Tags json serialization

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.