Integration of Spring and hibernate

Source: Internet
Author: User

1. Integration of spring and Hibernate 1.1. Create a sessionfactory in the spring container

To avoid hard-coded resource lookups that are tightly coupled with application objects, Spring allows you to define data access resources such as JDBC DataSource or hibernate sessionfactory in the spring container as beans. Any application object that requires access to the resource needs to hold references to these pre-defined instances only, and the following code shows how to create a JDBC DataSource and hibernate sessionfactory.

In the Applicationcontext.xml file, configure the following:

<bean id="DataSource" class="Org.apache.commons.dbcp.BasicDataSource">

<property name="Driverclassname" value="Oracle.jdbc.driver.OracleDriver">

</property>

<property name="url" value="JDBC:ORACLE:THIN:@127.0.0.1:1521:ORCL">

</property>

<property name="username " value="Scott"></property>

<property name="Password " value="Tiger" ></property>

</bean>

<bean id="Sessionfactory"

class="Org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="DataSource">

<ref bean="DataSource" />

</property>

<property name="Hibernateproperties">

<props>

<prop key="Hibernate.dialect">

Org.hibernate.dialect.Oracle9Dialect

</prop>

</props>

</property>

<property name="Mappingresources">

<list>

<value>

com/morris/school/DAO/entity/department.hbm.xml

</value>

</list>

</property>

</bean>

You can use the following in your application:

ApplicationContext ApplicationContext = new Classpathxmlapplicationcontext (

"Applicationcontext.xml");

Sessionfactory sessionfactory = (sessionfactory) applicationcontext

. Getbean ("Sessionfactory");

1.2. Implementation of DAO based on Hibernate3 native API

Departmentdapimpl.java

Package COM.MORRIS.SCHOOL.DAO.JDBC;

Import Org.hibernate.SessionFactory;

Import org.hibernate.Transaction;

Import org.hibernate.classic.Session;

Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Import Com.morris.school.dao.IDepartmentDao;

Import com.morris.school.dao.entity.Department;

public class Departmentdapimpl implements Idepartmentdao {

Private Sessionfactory sessionfactory;

Public Sessionfactory getsessionfactory () {

return sessionfactory;

}

public void Setsessionfactory (Sessionfactory sessionfactory) {

This.sessionfactory = sessionfactory;

}

public void Adddepartment (Department dept) {

Session session = Sessionfactory.opensession ();

Transaction Transaction = null;

try {

Transaction = Session.begintransaction ();

Session.save (dept);

Transaction.commit ();

} catch (Exception e) {

if (transaction! = NULL) {

Transaction.rollback ();

}

E.printstacktrace ();

} finally {

Session.close ();

}

}

}

The following configuration is in the spring configuration file:

<bean id= "Deptdao" class= "Com.morris.school.dao.jdbc.DepartmentDapImpl" >

<property name= "Sessionfactory" ref= "Sessionfactory" ></property>

</bean>

1.3. The DAO implementation based on spring

HibernateDaoSupportThe base class provides a function to access the object bound to the current transaction Session , thus guaranteeing the correct conversion of the exception in this case. Similar functions can be found in SessionFactoryUtils classes, but they appear in the form of static methods. It is important to note that the ' false ' as a parameter value (indicating whether creation is allowed) is usually passed to getSession(..) the method for invocation. At this point, the entire invocation is completed within the same transaction (its entire lifecycle is controlled by the transaction, avoiding the need to close the return Session ).

Package COM.MORRIS.SCHOOL.DAO.JDBC;

Import Org.hibernate.SessionFactory;

Import org.hibernate.Transaction;

Import org.hibernate.classic.Session;

Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Import Org.springframework.orm.hibernate3.support.HibernateDaoSupport;

Import Com.morris.school.dao.IDepartmentDao;

Import com.morris.school.dao.entity.Department;

public class Departmentdapimpl extends Hibernatedaosupport implements Idepartmentdao {

public static void Main (string[] args) {

ApplicationContext ApplicationContext = new Classpathxmlapplicationcontext (

"Applicationcontext.xml");

Idepartmentdao Deptdao = (Idepartmentdao) applicationcontext

. Getbean ("Deptdao");

Deptdao.adddepartment (New Department ("4", "logistics"));

}

public void Adddepartment (Department dept) {

This.gethibernatetemplate (). Save (dept);

}

}

1.4. Configuration of single transaction management

<!--target objects--

<bean id="Deptdao" class="Com.morris.school.dao.jdbc.DepartmentDapImpl">

<property name="sessionfactory" ref="Sessionfactory"></property>

</bean>

<!--Facets--

<bean id="TransactionManager"

class="Org.springframework.orm.hibernate3.HibernateTransactionManager">

<property name="sessionfactory" ref="Sessionfactory"></property>

</bean>

<!--proxy objects--

<bean id="Transactionproxy"

class="Org.springframework.transaction.interceptor.TransactionProxyFactoryBean">

<!--target objects--

<property name="target" ref="Deptdao"></property>

<!--Facets--

<property name="TransactionManager" ref="TransactionManager"></property>

<property name="Proxytargetclass" value="true">

</property>

<!--Property Templates--

<property name="Transactionattributes">

<props>

<prop key="add*">PROPAGATION_REQUIRED</prop>

<prop key="update*">PROPAGATION_REQUIRED</prop>

<prop key="delete*">PROPAGATION_REQUIRED</prop>

<prop key="insert*">PROPAGATION_REQUIRED</prop>

<prop key="save*">PROPAGATION_REQUIRED</prop>

<prop key="do*">PROPAGATION_REQUIRED</prop>

<prop key="query*">readOnly</prop>

<prop key="find*">readOnly</prop>

<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>

<!--

Propagation_required = = supports the current transaction and re-creates a transaction if no transaction is currently in service.

Propagation_supports = = supports the current transaction and executes non-transacted if no transaction is currently readonly = =

is read-only, the set operation permission is read-only, commonly used for querying

-

</props>

</property>

</bean>

1.5. Configuration of public affairs

<!--target objects--

<bean id="Deptdao" class="Com.morris.school.dao.jdbc.DepartmentDapImpl">

<property name="sessionfactory" ref="Sessionfactory"></property>

</bean>

<!--Facets--

<bean id="TransactionManager"

class="Org.springframework.orm.hibernate3.HibernateTransactionManager">

<property name="sessionfactory" ref="Sessionfactory"></property>

</bean>

<!--public affairs agent---

<bean id="Basetransactionproxy"

class="Org.springframework.transaction.interceptor.TransactionProxyFactoryBean"

abstract="True " lazy-init="true">

<!--Facets--

<property name="TransactionManager" ref="TransactionManager"></property>

<!--Property Templates--

<property name="Transactionattributes">

<props>

<prop key="add*">PROPAGATION_REQUIRED</prop>

<prop key="update*">PROPAGATION_REQUIRED</prop>

<prop key="delete*">PROPAGATION_REQUIRED</prop>

<prop key="insert*">PROPAGATION_REQUIRED</prop>

<prop key="save*">PROPAGATION_REQUIRED</prop>

<prop key="do*">PROPAGATION_REQUIRED</prop>

<prop key="query*">readOnly</prop>

<prop key="find*">readOnly</prop>

<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>

<!--

Propagation_required = = supports the current transaction and re-creates a transaction if no transaction is currently in service.

Propagation_supports = = supports the current transaction and executes non-transacted if no transaction is currently readonly = =

is read-only, the set operation permission is read-only, commonly used for querying

-

</props>

</property>

</bean>

<bean id="Userdaoproxy" parent="Basetransactionproxy">

<property name="target" ref="Deptdao"></property>

</bean>

Integration of Spring and hibernate

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.