SSH series: (5) Integrate spring and Hibernate

Source: Internet
Author: User


The key to spring and hibernate integration is that Hibernate's sessionfactory is created by the spring IOC container, and Hibernate's transactions are managed by spring's AOP. Note: Because of the integration, the configuration in Hibernate configuration file (Hibernate.cfg.xml) can be written to the spring configuration file, so you can delete the Hibernate.cfg.xml file .


Hibernate Pre-integration After integration
Sessionfactory Created by the developer Created by the spring IOC container
Transaction Maintained by the developer (fine-grained transactions) Dynamic injection by Spring AOP (coarse-grained transactions)


(1) Add jar Package

(2) Transfer hibernate configuration to spring configuration

(3) DAO Layer and service layer code preparation

(4) Inject the classes of the DAO Layer and service layer into the spring configuration

(5) test


1. Add Jar Package

Add Spring-aop, SPRING-JDBC, spring-orm related jar packages


SPRING-AOP Related JAR Packages


Aopalliance-.jar

Aspectjrt.jar

Aspectjweaver.jar

Spring-aop-3.2.5.release.jar



SPRING-JDBC Related JAR Packages


Spring-jdbc-3.2.5.release.jar

Spring-tx-3.2.5.release.jar



Spring-orm Related JAR Packages


Spring-orm-3.2.5.release.jar



2. Transfer hibernate configuration to spring configuration


2.1. Delete hibernate.cfg.xml files

Just delete the Hibernate.cfg.xml file

2.2. Add Bean-base.xml File

The main preservation of the original hibernate.cfg.xml in the configuration, mainly includes the following three aspects: Database connection Information, Hibernate Sessionfactory object creation and configuration, hibernate transaction management.

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "    xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "     xmlns:p= "http://www.springframework.org/schema/p"     xmlns:context= "http// Www.springframework.org/schema/context "    xmlns:tx=" Http://www.springframework.org/schema /tx "    xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "    xsi: Schemalocation= "        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd        &nbSp;http://www.springframework.org/schema/tx     http://www.springframework.org/schema /tx/spring-tx.xsd        http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop.xsd ">     <!--  Import External properties configuration file  --><context:property-placeholder  location= "Classpath:db.properties"  /><!--  Configure C3P0 data source  --><bean id= "DataSource"  class= "Com.mchange.v2.c3p0.ComboPooledDataSource" ><property name= "Driverclass"  value= "${ Driverclass} "></property><property name=" Jdbcurl " value=" ${jdbcurl} "></property ><property name= "User"  value= "${user}" ></property><property name= "password"  value= "${password}" ></property><!--get three connections when initializing, the value should be between Minpoolsize and Maxpoolsize. Default: 3 --><property&nbSp;name= "Initialpoolsize"  value= "${initialpoolsize}" ></property><!--the minimum number of connections kept in the connection pool. Default: 3 --><property name= "Minpoolsize"  value= "${minpoolsize}" ></property ><!--The maximum number of connections that are kept in the connection pool. Default: 15 --><property name= "Maxpoolsize"  value= "${maxpoolsize}" ></property ><!--c3p0 The number of connections that are fetched at the same time when the connection in the connection pool is exhausted. Default: 3 --><property name= "Acquireincrement"  value= "${acquireIncrement}" ></ property><!--Maximum idle time, unused in 1800 seconds, the connection is discarded, and if 0 is never discarded. Default: 0 --><property name= "MaxIdleTime"  value= "${maxidletime}" ></property ></bean><!-- <bean id= "DataSource"  class= " Com.mchange.v2.c3p0.ComboPooledDataSource "><property name=" Driverclass " value=" Com.mysql.jdbc.Driver "></property><property name=" Jdbcurl " value=" jdbc:mysql:// 127.0.0.1:3306/tax_sys "></property><property name=" user " value="Root" ></property><property name= "password"  value= "root" ></property>< Property name= "Initialpoolsize"  value= "3" ></property><property name= "MinPoolSize"  value= "3" ></property><property name= "Maxpoolsize"  value= "></property>" <property name= "Acquireincrement"  value= "3" ></property><property name= " MaxIdleTime " value=" 1800 "></property></bean> --><!-- sessionfactory - -><bean id= "Sessionfactory"  class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean" ><property name= "DataSource"  ref= "DataSource" ></property><property name= " Hibernateproperties "><props><prop key=" Hibernate.dialect "> org.hibernate.dialect.mysql5dialect</prop><prop key= "Hibernate.show_sql" >true</prop> <prop key= "Hibernate.format_sql" &GT;FALSE&LT;/PROP&GT;&LT;PRop key= "Hibernate.hbm2ddl.auto" >update</prop></props></property><property  Name= "Mappinglocations" ><list><value>classpath:com/rk/*/entity/*.hbm.xml</value></list ></property></bean><!--  Transaction Management  --><bean id= "Txmanager"  class= " Org.springframework.orm.hibernate3.HibernateTransactionManager "><property name=" Sessionfactory "  ref= "Sessionfactory" ></property></bean><!--  Transaction Notification  --><tx:advice id = "Txadvice"  transaction-manager= "Txmanager" ><tx:attributes><tx:method name= "find*"   Read-only= "true"/><tx:method name= "get*"  read-only= "true"/><tx:method name= "load*"  read-only= "true"/><tx:method name= "search*"  read-only= "true"/><tx:method name = "list*"  read-only= "true"/><tx:method name= "*"  read-only= "false"  rollback-for= " Throwable "/></tx:attributes></tx:advice><!--  Using AOP to implant transactions  --><aop:config><aop:pointcut id= "PT"  expression= "Bean (*service)"/><!-- <aop:pointcut id= "PT"  expression= "Execution (*  com.rk.test.service.impl.*.* (..)) " /> --><aop:advisor advice-ref= "Txadvice"  pointcut-ref= "PT"/></aop:config>< /beans>

In the above configuration, we have two locations optimized :

(1) Place the configuration parameters of the database in a db.properties file to save

driverclass=com.mysql.jdbc.driverjdbcurl=jdbc:mysql://127.0.0.1:3306/tax_sys?useunicode=true& Characterencoding=utf8user=rootpassword=rootinitialpoolsize=4minpoolsize=2maxpoolsize=12acquireincrement= 2maxidletime=1800

Also, note that this configuration in the Bean-base.xml file

<!--Import the external properties profile--><context:property-placeholder location= "Classpath:db.properties"/>


(2) Improvement of pointcut expressions when applying transactions

Originally

<aop:pointcut id= "PT" expression= "Execution (* com.rk.test.service.impl.*.* (..))" />

After the change

<aop:pointcut id= "pt" expression= "Bean (*service)"/>



2.3. Introduce the Bean-base.xml file into the Applicationcontext.xml file

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "    xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "     xmlns:p= "http://www.springframework.org/schema/p"     xmlns:context= "http// Www.springframework.org/schema/context "    xmlns:tx=" Http://www.springframework.org/schema /tx "    xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "    xsi: Schemalocation= "        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd        &nbSp;http://www.springframework.org/schema/tx     http://www.springframework.org/schema /tx/spring-tx.xsd        http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop.xsd "> <import resource= "Classpath:bean-base.xml"/></beans>

The point is the following sentence

<import resource= "Classpath:bean-base.xml"/>



3. DAO Layer and Service layer code preparation

Persondao.java

Package Com.rk.test.dao;import Java.io.serializable;import Com.rk.test.entity.person;public interface PersonDao { Person FindByID (Serializable id), void Save (Person P);}

Persondaoimpl.java

Package Com.rk.test.dao.impl;import Java.io.serializable;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Com.rk.test.dao.persondao;import Com.rk.test.entity.person;public Class Persondaoimpl implements Persondao {private sessionfactory sessionfactory;public void Setsessionfactory ( Sessionfactory sessionfactory) {this.sessionfactory = sessionfactory;} Public person FindByID (Serializable ID) {Session session = Sessionfactory.getcurrentsession (); Person P = (person) session.get (Person.class, id); return p;} public void Save (person p) {Session session = Sessionfactory.getcurrentsession (); Session.save (P);}}

Personservice.java

Package Com.rk.test.service;import Java.io.serializable;import Com.rk.test.entity.person;public interface Personservice {person FindByID (Serializable id), void Save (Person P);}

Personserviceimpl.java

Package Com.rk.test.service.impl;import Java.io.serializable;import Com.rk.test.dao.persondao;import Com.rk.test.entity.person;import Com.rk.test.service.personservice;public class Personserviceimpl implements Personservice {private Persondao persondao;public void Setpersondao (Persondao persondao) {This.persondao = PersonDao;} Public person FindByID (Serializable id) {//person p = new Person ();//p.setpname ("Little Red");//persondao.save (p); return Persondao.findbyid (ID);} public void Save (person p) {Persondao.save (P);//int i = 1/0;}}



4. Inject the classes of the DAO Layer and service layer into the spring configuration

Bean-dao.xml

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "    xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "     xmlns:p= "http://www.springframework.org/schema/p"     xmlns:context= "http// Www.springframework.org/schema/context "    xmlns:tx=" Http://www.springframework.org/schema /tx "    xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "    xsi: Schemalocation= "        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd        &nbSp;http://www.springframework.org/schema/tx     http://www.springframework.org/schema /tx/spring-tx.xsd        http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop.xsd "> <bean id= "Persondao"  class= "Com.rk.test.dao.impl.PersonDaoImpl" ><property name= " Sessionfactory " ref=" Sessionfactory "></property></bean></beans>

Bean-service.xml

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "    xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "     xmlns:p= "http://www.springframework.org/schema/p"     xmlns:context= "http// Www.springframework.org/schema/context "    xmlns:tx=" Http://www.springframework.org/schema /tx "    xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "    xsi: Schemalocation= "        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd        &nbSp;http://www.springframework.org/schema/tx     http://www.springframework.org/schema /tx/spring-tx.xsd        http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop.xsd "> <bean id= "Personservice"  class= "Com.rk.test.service.impl.PersonServiceImpl" ><property  Name= "Persondao"  ref= "Persondao" ></property></bean></beans>

Applicationcontext.xml introduces Bean-dao.xml, Bean-service.xml

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "    xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "     xmlns:p= "http://www.springframework.org/schema/p"     xmlns:context= "http// Www.springframework.org/schema/context "    xmlns:tx=" Http://www.springframework.org/schema /tx "    xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "    xsi: Schemalocation= "        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd        &nbSp;http://www.springframework.org/schema/tx     http://www.springframework.org/schema /tx/spring-tx.xsd        http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop.xsd "> <import resource= "Classpath:bean-base.xml"/><import resource= "classpath:com/rk/*/config/ Bean-*.xml "/></beans>

The point is the following sentence

<import resource= "Classpath:com/rk/*/config/bean-*.xml"/>


5. Testing

The test is divided into two ways:

(1) General test: Ability to read a piece of data, to be able to save a piece of data

(2) Transaction test: Cannot store data in read-only transactions, transaction exception to rollback

package com.rk.test;import org.junit.before;import org.junit.test;import  org.springframework.context.applicationcontext;import  org.springframework.context.support.classpathxmlapplicationcontext;import com.rk.test.entity.person; import com.rk.test.service.personservice;public class testmerge {private  applicationcontext ac; @Beforepublic  void init () {ac = new  Classpathxmlapplicationcontext ("Applicationcontext.xml");} @Testpublic  void testfindbyid () {personservice personservice =  (personservice)   Ac.getbean ("Personservice"); Person p = personservice.findbyid ("4028d081564ac44401564ac4478b0000"); SYSTEM.OUT.PRINTLN (P);} @Testpublic  void testsave () {personservice personservice =  (personservice)   Ac.getbean ("Personservice"); Person p = new person ();p. Setpname ("Lucy");p Ersonservice.save (p); @Testpublic  void testtransacTionreadonly ()//read-only transaction, rollback {personservice personservice =  (personservice) If an update operation occurs in a read-only transaction   Ac.getbean ("Personservice"); Person p = personservice.findbyid ("4028d081564ac44401564ac4478b0000"); SYSTEM.OUT.PRINTLN (P);} @Testpublic  void testtransactionrollback ()//rolls back the transaction and rolls back the previous operation if there is a task exception in the Operation {personservice  personservice =  (Personservice)  ac.getbean ("Personservice"); Person p = new person ();p. Setpname ("Lily");p Ersonservice.save (P);}}





SSH series: (5) Integrate 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.