Basic integration of Spring integration Hibernate (1)

Source: Internet
Author: User

Basic integration of Spring integrated Hibernate3


Spring integration Hibernate3 and 4 have a certain difference, the basic is currently using 3, so here the content is based on 3;
1. Import hibernate packages and Spring packages
1.1. Import a Spring dependency package
1.2. Import the log4j dependency package: Log4j-1.2.16.jar
1.3. Import the DBCP dependency package: Commons-dbcp-1.4.jar, Commons-pool-1.5.6.jar
1.4. Import the Hibernate3 dependency package
Hibernate all versions Address: http://sourceforge.net/projects/hibernate/files/hibernate3/

hibernate3.6.8 Version Address: http://sourceforge.net/projects/hibernate/files/hibernate3/3.6.8.Final/ Hibernate-distribution-3.6.8.final-dist.tar.gz/download
Hibernate contains packages: Hibernate3.jar, Slf4j-api-1.6.1.jar, JPA folders under package (annotation support). jar, required file all

2. Create Beans.xml
2.1. Create DataSource with DBCP (as with the integrated JDBC)
2.2. Create Hibernate sessionfactory

<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:14PX;" > <!--Create Sessionfactory factory-->    <bean id= "Sessionfactory"         class= "Org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" >         <property name= "DataSource" ref= "DataSource"/>        <!- -Set spring to go to that package to find the corresponding entity class-->        <property name= "Packagestoscan" >             <value>org.oms.spring.model</value>        </property>        <property name= " Hibernateproperties ">            <!--mode 2 <value>                 hibernate.dialect= org.hibernate.dialect.mysqldialect       &NBSP;&NBsp;       hibernate.show_sql=true                 hibernate.hbm2ddl.auto=update                 hibernate.format_sql=false            </value>-- >            <props>                 <prop key= "Hibernate.dialect" >org.hibernate.dialect.mysqldialect</ prop>                <prop key= "Hibernate.show_ SQL ">true</prop>                <prop key=" Hibernate.hbm2ddl.auto ">update</prop>                 <prop key= "Hibernate.format_sql" >false</prop>     &nbsP      </props>        </property>     </bean></span>





3. Add hibernate annotation or HBM files to the entity class.
4. Create a hibernate-based DAO
4.1. Inject the corresponding sessionfactory into the corresponding DAO;
4.2. If the corresponding Sessionfactory is managed through spring, No longer use factory.opensession () to open the session, but should be a factory.getcurrentsession to the session, the session will be managed by spring,
At this point the developer does not need to do things control, do not close the session, all by the spring container to complete!

5. Configure the processing of spring, only after the disposition of things, spring can effectively manage things;

<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:14PX;" ><!--Configure spring's things handling--><!--create things manager--><!--sessionfactory, DataSource, etc. omitted--><bean ID = "Txmanager" class= "Org.springframework.orm.hibernate3.HibernateTransactionManager" ><property name= " Sessionfactory "ref=" sessionfactory "/></bean><!--configuration aop,spring is the management of things through AOP--><aop:config> <!--setting Pointcut indicates which methods to add to the transaction--><aop:pointcut id= "Allmethods" expression= "Execution (* org.oms.spring.dao.* .*(..))" /><!--through the advisor to determine the specific way to add control of things--><aop:advisor advice-ref= "Txadvice" pointcut-ref= "Allmethods"/> </aop:config><!--Configure which methods to add the things control--><tx:advice id= "Txadvice" transaction-manager= "Txmanager" >< tx:attributes><!--Let all methods be added to the management of things--><tx:method name= "*" propagation= "REQUIRED"/></tx:attributes ></tx:advice></span> 


Note: In MySQL, when the data table name and the system table name are the same, the syntax error is reported when you perform an action using Hibernate!
Therefore, avoid using system table names.

Spring integrated Hibernate (1) Base integration Source code:

Specific implementation code:

In this paper, we implement integration based on the combination implementation of the design pattern of the JDBC template method in spring .

XML file configuration:

<?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:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/ Spring-aop-3.2.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.2.xsd "><!--Open the support of spring annotation--><context:annotation-config/><!-- Set spring to which packages to find annotation--><context:component-scan base-package= "org.oms.spring"/><!--Create data source <bean id= "DataSource" class= "Org.apAche.commons.dbcp.BasicDataSource "destroy-method=" Close "><property name=" Driverclassname "value=" ${ Jdbc.driverclassname} "/><property name=" url "value=" ${jdbc.url} "/><property name=" username "value=" ${ Jdbc.username} "/><property name=" password "value=" ${jdbc.password} "/><!--Configure the initial value of the connection pool--><property Name= "maxactive" value= "" "/><!--maximum idle time, after a peak, the connection pool can be used to release some of the fabric to the connection, has been reduced until Maxidle--><property name=" Maxidle "value="/><!--when minimum idle, some connections are automatically requested when the connection is less than Minidle--><property name= "Minidle" value= "1"/>< Property Name= "maxwait" value= "" "/></bean><!--import jdbc.properties--><context under src: Property-placeholder location= "jdbc.properties"/><!--create Sessionfactory factory--><!-- If you are using annotation mode, you cannot use Org.springframework.orm.hibernate3.LocalSessionFactoryBean, but you should use Org.springframework.orm.hibernate3 . Annotation. Annotationsessionfactorybean--><bean id= "sessionfactory" class= "Org.springframework.orm.hibernatE3.annotation.AnnotationSessionFactoryBean "><property name=" DataSource "ref=" DataSource "/><!-- Set spring to go to that package to find the corresponding entity class--><property name= "Packagestoscan" ><value>org.oms.spring.model</value ></property><property name= "hibernateproperties" ><!--<value> hibernate.dialect= Org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update hibernate.format_sql= False </value>--><props><prop key= "Hibernate.dialect" >org.hibernate.dialect.mysqldialect </prop><prop key= "Hibernate.show_sql" >true</prop><prop key= "Hibernate.hbm2ddl.auto" > Update</prop><prop key= "Hibernate.format_sql" >false</prop></props></property>< /bean><!--Configure spring's things handling--><!--create things manager--><!--sessionfactory, DataSource, etc. omitted-->< Bean id= "Txmanager" class= "Org.springframework.orm.hibernate3.HibernateTransactionManager" ><property name= " SessionfacTory "ref=" Sessionfactory "/></bean><!--configuration aop,spring is the--><aop:config>< of things managed through AOP!-- Set Pointcut to indicate which methods to add things to handle--><aop:pointcut id= "allmethods" expression= "Execution (* org.oms.spring.dao.*.* (..))" /><!--through the advisor to determine the specific way to add control of things--><aop:advisor advice-ref= "Txadvice" pointcut-ref= "Allmethods"/> </aop:config><!--Configure which methods to add the things control--><tx:advice id= "Txadvice" transaction-manager= "Txmanager" >< tx:attributes><!--Let all methods be added to the management of things (inefficient, on-demand processing in practice)--><tx:method name= "*" propagation= "REQUIRED"/></ Tx:attributes></tx:advice></beans>

Basedao class, this class is extracted from the Public configuration section!
Package Org.oms.spring.dao;import Javax.annotation.resource;import Org.hibernate.session;import Org.hibernate.sessionfactory;public class Basedao {private Sessionfactory sessionfactory;public SessionFactory Getsessionfactory () {return sessionfactory;} /** * Name consistent can not write name *  * @param sessionfactory */@Resource (name = "Sessionfactory") public void Setsessionfactory ( Sessionfactory sessionfactory) {this.sessionfactory = sessionfactory;} Protected session getsession () {//Get session, note that opensession () is not used. Getcurrentsession () return Sessionfactory.getcurrentsession ();}}

Userhibernatedao class
Package Org.oms.spring.dao;import Java.util.list;import Javax.annotation.resource;import org.hibernate.Query; Import Org.oms.spring.model.group;import Org.oms.spring.model.user;import org.springframework.stereotype.repository;/** * User Hibernate-based crud * @author Sunlight * */@Repository (" Userhibernatedao ") public class Userhibernatedao extends Basedao implements Iuserdao {private Igroupdao Grouphibernatedao;public Igroupdao Getgrouphibernatedao () {return grouphibernatedao;} @Resourcepublic void Setgrouphibernatedao (Igroupdao grouphibernatedao) {This.grouphibernatedao = Grouphibernatedao;} @Overridepublic void Add (user user, int gid) {Group group=grouphibernatedao.load (GID); User.setgroup (group); getsession (). Save (user); @Overridepublic void Update (user user, int gid) {Group group=grouphibernatedao.load (GID); User.setgroup (group); GetSession (). Update (user); @Overridepublic void Delete (int id) {User user=this.load (ID); getsession (). Delete (user);} @Overridepublic user load (int id) {return (user) getSession (). Load (user.class, id);} @SuppressWarnings ("unchecked") @Overridepublic list<user> List (String sql, object[] args) {//Here based on HQL query, so sleepy! Query query=this.getsession (). CreateQuery (SQL), if (Query!=null) {for (int i = 0; i < args.length; i++) { Query.setparameter (i, args[i]);}} return Query.list ();}}

Grouphibernatedao class
Package Org.oms.spring.dao;import Org.oms.spring.model.group;import org.springframework.stereotype.repository;/** * Group Hibernate-based CRUD * @author Sunlight * */@Repository ("Grouphibernatedao") public class Grouphibernatedao extends Basedao implements Igroupdao {@Overridepublic void Add (group group) {//getsession is obtained by Getcurrentsession to get the session, It will be managed by spring, so no other action is required getsession (). Save (group); @Overridepublic the group load (int id) {//load () method error, delay loading problem, which is described later, here using the Get method return (Group) getsession (). Get (Group.class, ID);}}

Here you need to add annotations on the entity class:

Group.class

Add Annotations @Entity @table (name= "T_group") primary key @id@generatedvalue

User.class
Add annotations on the primary key of the @Entity @table (name= "T_user") @id@generatedvalue foreign keys Add annotations @manytoone@joincolumn (name= "GID")

Package class Diagram:


Test class and results:





Basic integration of Spring integration Hibernate (1)

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.