Spring solves the JPA delay loading problem in the MVC layer

Source: Internet
Author: User
Tags aop config parent directory requires

As part of EJB3.0, JPA is a good thing. Its simple configuration and powerful default configuration support, make it easy and free to exist between light weight and weight, if your Java EE project now chooses lightweight or heavyweight architecture, if the persistence layer does not choose to use JPA, it uses some ORM frameworks (such as Hibernate, TopLink) Special API, then one day in the future will certainly for this choice and say the supreme treasure that sentence "If God give me another chance ..." the wisdom.
The following is a simple entity, which is the definition of a tree-like information directory entity class in a CMS system, including some detailed mapping of configuration information. @Entity
public class Newsdir ... {
@Id
@GeneratedValue (strategy = generationtype.table)
Private Long id;//PRIMARY key

@Column (unique = true, Nullable = false, length = 16)
Private String sn;//Directory number

Private String title; Directory Name

@OneToMany (Mappedby = "parent", cascade = Javax.persistence.CascadeType.REMOVE)
Private list<newsdir> children = new java.util.arraylist<newsdir> ()//Subordinate Directory

@ManyToOne
Private Newsdir parent;//Parent Directory

...

}
Of course, like any other good technology, JPA is not perfect, in the use of the process will inevitably have such a problem, which requires our programmers have the ability to scientia in the application flexibility to deal with these problems.
Here's an example of a slow-Changaca problem, taking the news directory above entity as an example. For parnet and children this one-to-many two-way association, in order to improve the efficiency of the system, children default is to use the slow Changaca way. In some lightweight architectures, because of the absence of Java-EE containers and transaction support, entity is often removed from the persitence context, turned into a detach or entitymanager shutdown, leading to some of the features we envision not functioning properly.
The most common is that when you use the MVC framework, you cannot load data that requires slow Changaca at the presentation layer. For example, in an MVC application based on Easyjweb, the action method is as follows:

Public Page dolist (WebForm form, module module) ... {
Newsdirqueryobject Ndqo = new Newsdirqueryobject ();
Form.topo (NDQO);
Ndqo.setdel (TRUE);
Ipagelist pagelist = service.querydirsbyconditions (NDQO);
Commutilforteaec.saveipagelist2webform (pagelist, form);
Form.addresult ("Dirpath", This.getdirpath (form));
return module.findpage ("list");
}
In the template file, you have the following contents:
#foreach ($info in ${dir.children})
Directory Name: ${info.title}
#end

About the configuration of the business Logic Layer Bean:

<aop:config>
<aop:pointcut id= "cmsmanage"
expression= "Execution (* com.easyjf.cms.service.*.* (..))" />
<aop:advisor advice-ref= "Cmsmanageadvice"
pointcut-ref= "Cmsmanage"/>
<tx:advice id= " Cmsmanageadvice "
transaction-manager=" TransactionManager
<tx:attributes>
<tx:method Name = "get*" propagation= "SUPPORTS"
read-only= "true"/>
<tx:method name= "query*" propagation= "SUPPORTS"
Read-only= "true"/>
<tx:method name= "*" propagation= "REQUIRED"/>
</tx:attributes>
</tx : Advice>
<bean id= "Cmsmanageservice"
class= "Com.easyjf.cms.service.impl.CmsManageServiceImpl" >
<property name= "Newsdirdao" ref= "Newsdirdao"/>
</bean>
here, when the MVC layer executes to $!info.getchildren () method, the deferred load is used, because spring's transactions are configured at the service level, so the transaction is closed after the Service.querydirsbyconditions method is completed. As a result, running the program will cause an error message similar to the following:

2007-03-28 00:39:35,750 ERROR [Org.hibernate.LazyInitializationException]-Failed to lazily initialize a collection o F Role:com.easyjf.cms.domain.NewsDir.children, no session or session is closed
Org.hibernate.LazyInitializationException:failed to lazily initialize a collection's role: Com.easyjf.cms.domain.NewsDir.children, no session or session is closed
at Org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException ( abstractpersistentcollection.java:358)
at Org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected ( abstractpersistentcollection.java:350)
at Org.hibernate.collection.AbstractPersistentCollection.readSize ( ABSTRACTPERSISTENTCOLLECTION.JAVA:97)

The problem with other MVC such as struts, webwork, and spring MVC is that at the core of the problem is the fact that at the start and end of a transaction, we are accustomed to configuring and using transactions at the service level rather than MVC. The solution is actually very simple, that is, the start of the transaction into the MVC layer,
Let the MVC layer controller to open the transaction and let the business layer's methods join the transaction. For example, in Easyjweb, implementations can be implemented to open transactions in action by using the following configuration:
Configure the Easyjweb core processor in the spring configuration file and add the process method to the transaction with the following configuration file:

<aop:config>
<aop:pointcut id= "Easyjwebprocessor"
expression= "Execution (* com.easyjf.web.RequestProcessor.process (..))"/>
<aop:advisor advice-ref= "Txeasyjwebprocessoradvice"
pointcut-ref= "Easyjwebprocessor"/>
</aop:config>
<tx:advice id= "Txeasyjwebprocessoradvice"
Transaction-manager= "TransactionManager" >
<tx:attributes>
<tx:method name= "*" propagation= "REQUIRED" read-only= "true"/>
</tx:attributes>
</tx:advice>
<bean name= "Easyjweb-processor" class= "Com.easyjf.web.core.DefaultRequestProcessor"/>
With just such a simple configuration, you will be surprised to find that all the slow Changaca and other problems caused by the persitence context are resolved.

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.