Spring solves the slow loading problem of JPA at the MVC layer.

Source: Internet
Author: User
As part of ejb3.0, JPA is a good thing. Its simple configuration method and powerful default configuration support make it easy and free to exist between lightweight and weight. If your javaee project is in the Light-weight architecture or heavyweight architecture, if the persistence layer does not use JPA, but uses specialized APIs of some ORM frameworks (such as Hibernate and toplink, in the future, we will say "If God gives me another chance..." for this choice ..." Famous saying.
The following is a simple entity, which defines the object class of the tree information directory in a CMS system, including some detailed ing configuration information.

@ Entity
Public class newsdir ...{
@ ID
@ Generatedvalue (Strategy = generationtype. Table)
Private long ID; // The primary key.

@ Column (unique = true, nullable = false, length = 16)
Private string Sn; // directory ID

Private String title; // directory name

@ Onetomany (mappedby = "parent", cascade = javax. Persistence. cascadetype. Remove)
Private list <newsdir> Children = new java. util. arraylist <newsdir> (); // sub-directory

@ Manytoone
Private newsdir parent; // parent directory

...

}
Of course, like any other excellent technology, JPA is not perfect. This problem will inevitably occur in the process of use. This requires our programmers to have the ability to understand things, flexible handling of these problems in applications.
Here is an example of slow loading. The entity of the above news directory is used as an example. For the one-to-multiple bidirectional association between parnet and children, children uses the slow loading method by default to improve system efficiency. In some lightweight architectures, due to the absence of J2EE containers and transaction support, entity often disconnects from the persitence context and changes to detach or entitymanager, as a result, some of the features we expected will not work properly.
The most common is that when using the MVC framework, data that needs to be loaded slowly cannot be loaded in the presentation layer. For example, in an easyjweb-based MVC application, the action method is as follows:

Public page dolist (webform form, 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 ");
}
The template file contains the following content:
# Foreach (in)
Directory Name:
# End

Bean configuration in the business logic layer:

 

<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 is executed to $! Info. the getchildren () method will use the slow loading function. Since spring transactions are configured at the service layer, services are executed. after the querydirsbyconditions method is completed, the transaction is closed. Therefore, an error message similar to the following occurs when you run the program:

00:39:35, 750 error [org. hibernate. lazyinitializationexception]-failed to lazily initialize a collection of Role: COM. easyjf. CMS. domain. newsdir. Children, no session or session was closed
Org. hibernate. lazyinitializationexception: failed to lazily initialize a collection of Role: COM. easyjf. CMS. domain. newsdir. Children, no session or session was 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)

Other MVC, such as struts, webwork, and even spring MVC, have such problems. The core of the problem is the start and end of the transaction, we are all used to configuring and using transactions on the service layer rather than MVC, leading to such problems. The solution is actually very simple. It is to put the startup of the transaction on the MVC layer,
Let the controller of the MVC layer start the transaction, and let the business layer method join the transaction. For example, in easyjweb, you can use the following configuration to enable transactions in action:
Configure the easyjweb core processor in the spring configuration file and add the process method to the transaction. The configuration file is as follows:

 

<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 this simple configuration, you will be surprised to find that all the slow loading and other problems caused by Invalid persitence context are solved.

 

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.