Delayed loading and Dao modes of Hibernate and spring

Source: Internet
Author: User
Reproduced in: http://spaces.msn.com/members/zcgly/Blog/cns! 1pqwdnsfbx4siamzphr2gqmq! 121. Entry

Delayed loading and Dao modes of Hibernate and spring
Original article: http://www.jroller.com/page/kbaum/20040708
By Karl Baum
Translator: zcugly time: 2005-07-13hibernate and delayed Loading
Hibernate object relationship ing provides two object initialization modes: delayed loading and non-delayed loading. Get the object itself and all objects associated with it during non-delayed loading. This may cause hundreds of select statements to be executed when an instance is obtained. When two-way Association is used, this problem is amplified. When initialization requests occur, the entire database is loaded. Obviously, we check the relationship between each object and manually delete their membership dues, but in the end we may lose the advantages of using the ORM tool. A detailed solution is to use the delayed loading mechanism provided by hibernate. This initialization policy only loads the one-to-many and many-to-many relationships of one of its objects when a class member is accessed. For developers, this method is transparent, and only a minimum number of requests occur, so as to achieve the best performance. One disadvantage of this technology is that delayed loading requires that the hibernate session must be enabled when the object is still in use. This raises an important issue when attempting to abstract the persistent layer through the DAO mode. To fully abstract the persistence layer, all database logic, including opening and closing sessions, cannot appear at the application layer. The most common is that these logics are hidden in the DAO implementation class. The quick and bad solution is to avoid using DAO mode and include the data connection logic in the application layer. This is feasible in small applications, but in large systems, this is a design defect that damages the scalability of applications. Use delayed loading on the web layer
Fortunately, the Spring framework has provided a web solution that combines DAO mode with hibernate delayed loading. For anyone who is not familiar with Spring framework and hibernate, I will not go into details here, but I hope you will read the section "accessing hibernate databases with Spring framework. This is a Web application. Spring provides opensessioninviewerfilter and opensessioninviewinterceptor. Use any of them to obtain the same function. The only difference between the two is that interceptor runs in the spring container and is configured in the context of the Web application. fitler runs before spring and is configured in Web. xml. No matter which one is used, they will open the hibernate session during the current thread of the Request bound to the session. Once bound to a thread, the opened hibernate session can be transparently used by the DAO implementation class. The session will continue to open to allow delayed loading of database access. Once the view logic is complete, the hibernate Session will be closed, whether in the dofilter method of filter or in the posthandle method of interceptor. The following is a configuration instance:
Interceptor configuration <beans>
<Bean id = "urlmapping"
Class = "org. springframework. Web. servlet. handler. simpleurlhandlermapping">
<Property name = "interceptors">
<List>
<Ref bean = "opensessioninviewinterceptor"/>
</List>
</Property>
<Property name = "mappings">
...
</Bean>
...
<Bean name = "opensessioninviewinterceptor"
Class = "org. springframework. Orm. hibernate. Support. opensessioninviewinterceptor">
<Property name = "sessionfactory"> <ref bean = "sessionfactory"/> </property>
</Bean>
</Beans> filter configuration <web-app>
...
<Filter>
<Filter-Name> hibernatefilter </filter-Name>
<Filter-class>
Org. springframework. Orm. hibernate. Support. opensessioninviewfilter
</Filter-class>
</Filter>
...
<Filter-mapping>
<Filter-Name> hibernatefilter </filter-Name>
<URL-pattern> *. Spring </url-pattern>
</Filter-mapping>
...
</Web-app>
It is very easy to use the hibernatedao implementation class of the opened session. In fact, if you have used the Spring framework to implement the DaO object of hibernate, it is most likely that you do not need to make any changes. Dao must access hibernate through the convenient hibernatetemplate tool, which is a piece of cake for database access. The following is an instance of Dao.
Dao instance public class hibernateproductdao extends hibernatedaosupport implements productdao {public product getproduct (integer productid ){
Return (product) gethibernatetemplate (). Load (product. Class, productid );
} Public integer saveproduct (product ){
Return (integer) gethibernatetemplate (). Save (product );
} Public void updateproduct (product ){
Gethibernatetemplate (). Update (product );
}
} Use delayed loading at the Business Layer
Even at the presentation layer, the Spring framework also provides convenient delayed loading support through the AOP interceptor hibernateinterceptor. The Hibernate interceptor transparently intercepts the call of the Business Object configured in the spring application context, opens the hibernate session before the call, and closes the session at the end of the call. Let's use a simple example. Suppose we have an interface called bussinessobject:
Public interface businessobject {
Public void dosomethingthatinvolvesdaos ();
}
Class businessobjectimpl implements the businessobject interface:
Public class businessobjectimpl implements businessobject {
Public void dosomethingthatinvolvesdaos (){
// Lots of logic that CILS
// Dao classes which access
// Data Objects lazily
}
}
Through some spring context configurations, we can allow hibernateinterceptor to intercept calls to businessobjectimpl, and allow its methods to delay access to data objects. Take a look at the following parts of the notebook:
<Beans>
<Bean id = "hibernateinterceptor" class = "org. springframework. Orm. hibernate. hibernateinterceptor">
<Property name = "sessionfactory">
<Ref bean = "sessionfactory"/>
</Property>
</Bean>
<Bean id = "businessobjecttarget" class = "com. acompany. businessobjectimpl">
<Property name = "somedao"> <ref bean = "somedao"/> </property>
</Bean>
<Bean id = "businessobject" class = "org. springframework. AOP. Framework. proxyfactorybean">
<Property name = "target"> <ref bean = "businessobjecttarget"/> </property>
<Property name = "proxyinterfaces">
<Value> com. acompany. businessobject </value>
</Property>
<Property name = "interceptornames">
<List>
<Value> hibernateinterceptor </value>
</List>
</Property>
</Bean>
</Beans>
When the businessobject instance is referenced, hibernateinterceptor opens a hibernate session and allows calls to bussinessobjectimpl. When businessojbectimpl is executed, hibernateinterceptor closes the session transparently. The application code does not know any persistence layer logic, but it can still load access data objects with delay. Use delayed loading in Unit Tests
Finally, we will test our delayed Loading application in JUnit. It is very easy to override the setup and teardown methods of the testcase class. I prefer to put this code in a simple abstract testcase class as the base class for all my tests.
Public abstract class mylazytestcase extends testcase {
Public void setup () throws exception {
Super. Setup ();
Sessionfactory = (sessionfactory) getbean ("sessionfactory ");
Session S = sessionfactory. opensession ();
Transactionsynchronizationmanager. bindresource (sessionfactory, new sessionholder (s);} protected object getbean (string beanname ){
// Code to get objects from spring application context
}
 
Public void teardown () throws exception {
Super. teardown ();
Sessionholder holder = (sessionholder) transactionsynchronizationmanager. getresource (sessionfactory );
Session S = holder. getsession ();
S. Flush ();
Transactionsynchronizationmanager. unbindresource (sessionfactory );
Sessionfactoryutils. closesessionifnecessary (S, sessionfactory );
}
}

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.