Integration of spring and hibernate from the perspective of implementation functions

Source: Internet
Author: User

1. Manage sessionfactory

When we use spring to integrate hibernate, we do not need the hibernate. cfg. xml file. First, configure the data source bean and session factory bean in applicationcontext. xml. When configuring the session factory bean, the following information should be injected:

● Data source Bean

● Configuration files for all persistence classes

● Attributes of sessionfactory of Hibernate

The attributes of sessionfactory of hibernate include the following: 1. Connection Method of hibernate; 2. Selection of different database connections during startup.

2. Inject the sessionfactory object into the hibernatetemplate and use the hibernatetemplate to persist the object.

Spring provides hibernatetemplate for persistent layer access. This template does not need to open or close sessions. As long as it gets the reference of sessionfactory, it can only open the session and close the session after the persistent access ends. The program development only needs to complete the persistence layer logic, for general operations (such as adding, deleting, modifying, and querying data in the database), hibernatetemplate is complete.

Hibernatetemplate has three constructor functions. To enable hibernatetemplate to complete persistence operations, you must pass in a reference to sessionfactory.

Hibernatetemplate can be used in either conventional or complex ways.

I. general usage

Hibernatetemplate can add, delete, modify, and delete most Dao objects by using common methods such as Delete (Object entity), find (string querystring), and save (Object entity, query.

Ii. complex usage

The complex usage of hibernatetemplate is achieved through the following two methods:

● Object execute (hibernatecallback action)

● List execute (hibernatecallback action)

Both methods require a hibernatecallback instance. Through hibernatecallback, program developers can access the database in a flexible way using hibernate. This solves the flexibility deficiency of hibernate Encapsulation by spring. Hibernatecallback is an interface with only one method doinhibernate (Org. hibernate. Session session). This method has only one parameter session.

Generally, the program uses an anonymous internal class that implements hibernatecallback to obtain the instances of hibernatecallback. doinhibernate is a persistent operation executed by spring. The code example is as follows:

Public class persondaoimpl {

Private sessionfactory;

Public void setsessionfactory (sessionfactory ){

This. sessionfactory = sessionfactory;

}

Public list findpersonbyname (final string name ){

Hibernatetemplate =

New hibernatetemplate (this. sessionfactory );

Return (listmediahibernatetemplate.exe cute (

Public object doinhibernate (session) throws hibernate exception {

List result = session. createcriteria (person. clsss)

. Add (restrictions. Like ("name", name + "%"). List ();

Return result;

}

);

}

}

Note: You can access the session in method doinhibernate. The session object is bound to the session instance of the thread, the persistent layer operations in this method are exactly the same as those when spring is not used. This ensures that hibernate can still be used for complex persistent layer access.

3. DAO implementation

There are two ways to implement Dao: 1. inherit from hibernatedaosupport to implement Dao; 2. Implement Dao Based on hibernate3.0.

1. inherit from hibernatedaosupport to implement Dao

Spring provides the tool class hibernatedaosupport for hibernate Dao. This class provides the following two methods to facilitate DAO implementation:

● Public final hibernatetemplate gethibernatetemplate ()

● Public final void setsessionfactory (sessionfactory)

The setsessionfactory method is used to receive sessionfactory instances from spring applicationcontext dependency injection. The gethibernatetemplate method is used to generate sessions based on the sessionfactory, And the hibernatetemplate is used to access the database.

2. Implement Dao Based on hibernate3.0

When Hibernate is under Transaction Management (usually Spring provides Transaction Management for hibernate), the current session can be returned through the getcurrentsession () method of sessionfactory, if the session associated with the current JTA transaction does not exist, the system opens a new session and associates it with the current JTA transaction. If the session associated with the current JTA transaction already exists, the session is returned directly. After obtaining the current session, you can perform the persistence operation.

It can be seen that no matter which method is used to implement Dao, spring must be used to inject sessionfactory instances.

4. Transaction Management

Hibernate suggests that all accesses to the database should be performed in the transaction, even if only the read operation is performed. Spring supports both programmatic and clear transactions. Declarative transactions are generally recommended.

Programmatic transaction management:

A programmatic transaction provides a transactiontemplate template class, which must provide a platformtransactionmanager instance to its body. As long as the transactiontemplate gets the reference of platformtransactionmanager, The transactiontemplate can complete the transaction operation. Transactiontemplate provides an execute method that receives a transactioncallback instance. Transactioncallback includes the following methods:

● Object dointransaction (transactionstatus status)

This requires a return value. If no return value is required, we can use the transactioncallbackwithoutresult class to replace the transactioncallback class. It also has a method:

● Void dointransaction (transactionstatus status)

In the two methods, when an exception occurs, the instance status of transactionstatus can be rolled back by calling the setrollbackonly () method.

Generally, an instance of transactioncallback or transactioncallbackwithoutresult is passed into the execute method in the form of an anonymous internal class.

Declarative transaction management:

Declarative transaction management is usually configured in three ways:

● Use transactionproxyfactorybean to generate the transaction proxy configuration for the target bean.

● Beannameautoproxycreator is used to automatically generate transaction proxy Based on bean name. This is a way to directly use spring's AOP framework to configure transaction proxy. You need to understand spring's AOP framework.

● Defaultadvisorautoproxycreator is used to directly configure the transaction proxy using spring's AOP framework. However, this configuration method is not as readable as beannameautoproxycreator.
------------------------------------------------------------------

<? XML version = "1.0" encoding = "UTF-8"?>

<Beans xmlns = "http://www.springframework.org/schema/beans"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd ">

<! -- Data source -->
<Bean id = "datasource" class = "org. Apache. commons. DBCP. basicdatasource" Destroy-method = "close">
<Property name = "driverclassname">
<Value> com.ibm.db2.jdbc.net. db2driver </value>
</Property>
<Property name = "url">
<Value> JDBC: DB2: // localhost: 6789/guoziwei </value>
</Property>
<Property name = "username">
<Value> db2admin </value>
</Property>
<Property name = "password">
<Value> db2admin </value>
</Property>
</Bean>
 
<! -- Database session factory -->
<Bean id = "sessionfactory" class = "org. springframework. Orm. hibernate3.localsessionfactorybean">
<Property name = "datasource">
<Ref local = "datasource"/>
</Property>
<Property name = "mappingresources">
<List>
<Value> COM/becom/INS/DTO/user. HBM. xml </value>
<Value> COM/becom/INS/DTO/insfunds. HBM. xml </value>
<Value> COM/becom/INS/DTO/company. HBM. xml </value>
<Value> COM/becom/INS/DTO/group. HBM. xml </value>
<Value> COM/becom/INS/DTO/otherfunds. HBM. xml </value>
</List>
</Property>

<Property name = "hibernateproperties">
<Props>
<Prop key = "hibernate. dialect"> org. hibernate. dialect. oracle9dialect </prop>
<Prop key = "hibernate. show_ SQL"> true </prop>
<Prop key = "hibernate. cglib. use_reflection_optimizer"> true </prop>
</Props>
</Property>
</Bean>

<! -- Transaction Manager -->
<Bean id = "transactionmanager" class = "org. springframework. Orm. hibernate3.hibernatetransactionmanager">
<Property name = "sessionfactory"> <ref local = "sessionfactory"/> </property>
</Bean>
 
<! -- Spring Transaction Manager Proxy -->
<Bean id = "transactionproxyfactory" abstract = "true" lazy-init = "true" class = "org. springframework. transaction. Interceptor. transactionproxyfactorybean">
<Property name = "transactionmanager">
<Ref local = "transactionmanager"/>
</Property>
<Property name = "transactionattributes">
<Props>
<Prop key = "Save *"> propagation_required </prop>
<Prop key = "insert *"> propagation_required </prop>
<Prop key = "del *"> propagation_required </prop>
<Prop key = "add *"> propagation_required </prop>
<Prop key = "Update *"> propagation_required </prop>
<Prop key = "find *"> propagation_required, readonly </prop>
<Prop key = "Search *"> propagation_required, readonly </prop>
<Prop key = "Remove *"> propagation_required, readonly </prop>
<Prop key = "query *"> propagation_required, readonly </prop>
<Prop key = "list *"> propagation_required, readonly </prop>
<Prop key = "count *"> propagation_required, readonly </prop>
<Prop key = "get *"> propagation_required, readonly </prop>
</Props>
</Property>
</Bean>

<! -- Hibernate template -->
<Bean id = "hibernatetemplate" class = "org. springframework. Orm. hibernate3.hibernatetemplate">
<Property name = "sessionfactory">
<Ref local = "sessionfactory"/>
</Property>
</Bean>

<! -- User service object -->
<Bean id = "userservice" parent = "transactionproxyfactory">
<Property name = "target">
<Bean class = "com. becom. INS. User. Service. userservice">
<Property name = "userdao">
<Ref local = "userdao"/>
</Property>
</Bean>
</Property>
</Bean>
 
<! -- User Data Access Object -->
<Bean id = "userdao" class = "com. becom. INS. User. Dao. userdao">
<Property name = "hibernatetemplate" ref = "hibernatetemplate"/>
</Bean>
 
<! -- Target of the bankruptcy service -->
<Bean id = "insservice" parent = "transactionproxyfactory">
<Property name = "target">
<Bean class = "com. becom. INS. Insolvency. Service. insfundsservice">
<Property name = "insdao">
<Ref local = "insdao"/>
</Property>
</Bean>
</Property>
</Bean>
 
<! -- User Data Access Object -->
<Bean id = "insdao" class = "com. becom. INS. Insolvency. Dao. insfundsdao">
<Property name = "hibernatetemplate" ref = "hibernatetemplate"/>
</Bean>
 
<! -- Group service targets -->
<Bean id = "groupservice" parent = "transactionproxyfactory">
<Property name = "target">
<Bean class = "com. becom. INS. Group. Service. groupserviceimpl">
<Property name = "groupdao">
<Ref local = "groupdao"/>
</Property>
</Bean>
</Property>
</Bean>
 
<! -- User Data Access Object -->
<Bean id = "groupdao" class = "com. becom. INS. Group. Dao. groupdaoimpl">
<Property name = "hibernatetemplate" ref = "hibernatetemplate"/>
</Bean>

<! -- Company service targets -->
<Bean id = "companyservice" parent = "transactionproxyfactory">
<Property name = "target">
<Bean class = "com. becom. INS. Company. Service. companyserviceimpl">
<Property name = "companydao">
<Ref local = "companydao"/>
</Property>
</Bean>
</Property>
</Bean>
 
<! -- Company Data Access Object -->
<Bean id = "companydao" class = "com. becom. INS. Company. Dao. companydaoimpl">
<Property name = "hibernatetemplate" ref = "hibernatetemplate"/>
</Bean>
 
</Beans>

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.