Spring Nineth "Spring and Hibernate integration"

Source: Internet
Author: User
Tags commit connection pooling generator xmlns
Preface

We've learned how to use spring to integrate with STRUTS2, and this post focuses on how to use spring to integrate Hibernate

Key points for Spring and hibernate consolidation: The Sessionfactory object is given to spring to create hibernate transactions to be managed by spring Spring and Hibernate integration steps introduce jar package connection pool/Database driver package Hibernate related jar Spring Core pack (5) Spring AOP package (4) Spring-orm-3.2.5.release.jar "Spring support for Hibernate" Spring-tx-3.2.5.release.jar "Transaction related"

configuration file hibernate.cfg.xml bean.xml

Bean.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"
       xsi:schemalocation= "http// Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">

</beans>

Hibernate.cfg.xml

 
build configuration Environment TestUser
package BB;

/**
 * Created by Ozc on 2017/5/15.
 */Public
class User {

    private String name;
    private String password;
    private int id;

    public int getId () {
        return ID;
    }

    public void setId (int id) {
        this.id = ID;
    }

    Public String GetName () {
        return name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    Public String GetPassword () {
        return password;
    }

    public void SetPassword (String password) {
        this.password = password;
    }

    @Override public
    String toString () {
        return "user{" +
                "name= '" + name + ' \ ' +
                ", password= ' + passwo Rd + ' \ ' +
                '} ';}
}
Iuser interface
Public interface Iuser {
    void Save ();
}
Userdao
public class Userdao implements Iuser {

    @Override public
    Void Save () {

    }

}
UserService
public class UserService {

    private Userdao Userdao;

    public void Save () {
        userdao.save ();
    }
}
testing the Spring environment

First, we use spring for Userdao, userservice to create objects, and to add dependencies on objects to see if spring's environment successfully created the Userdao instance @Repository

@Repository public
class Userdao implements Iuser {

    @Override public
    Void Save () {

    }

}
Create an UserService instance and inject the Userdao property

@Service public
class UserService {

    @Autowired
    private Userdao Userdao;

    public void Save () {
        userdao.save ();
    }
}
Using the note scanner in the spring configuration 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:context= "http://www.springframework.org/ Schema/context "
       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 ">

    <context:component-scan base-package=" BB " />

</beans>
Test: the UserService object is successfully obtained, and the UserService object contains the value of the Userdao property
public class Test2 {

    @Test public
    void Test33 () {
        ApplicationContext ac = new Classpathxmlapplicationcontext ("Spring-config.xml");


        UserService UserService = (userservice) ac.getbean ("UserService");
        System.out.println (UserService);
    }
}

test Hibernate Environment mapping configuration file

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE hibernate-mapping public 
    "-//hibernate/hibernate mapping DTD 3.0//en"
    "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">

master configuration file Load mapping file
        <mapping resource= "Bb/user.hbm.xml"/>
Create Sessionfactory,session
@Repository public
class Userdao implements Iuser {

    @Override public
    void Save (user user) {

        // Get sessionfactory
        sessionfactory sessionfactory = new Configuration (). Configure (). Buildsessionfactory ();

        Get session Session Session
        = Sessionfactory.opensession ();
        Session.begintransaction ();

        Session.save (user);

        Session.gettransaction (). commit ();
        Session.close ();
    }

}
Test:
public class Test2 {

    @Test public
    void Test33 () {
        ApplicationContext ac = new Classpathxmlapplicationcontext ("Spring-config.xml");


        UserService UserService = (userservice) ac.getbean ("UserService");
        Userservice.save (New User ());

    }
}

Create a Sessionfactory object using spring

One of the key points of spring and hibernate integration is to use spring to create Sessionfactory objects. There are three ways to create a sessionfactory Direct load Hibernate master profile

    <!--
        Sessionfactory is a factory, we want to use its implementation class
        we use the 3.6 version of Hibernate, so the load is 3-

    -
    <bean id= " Sessionfactory "class=" Org.springframework.orm.hibernate3.LocalSessionFactoryBean ">

        <!--explains where the configuration file is located-- >
        <property name= "configlocation" value= "Classpath:hibernate.cfg.xml"/>
    </bean>

Then in Userdao we do not have to manually create the Sessionfactory object.

@Repository public
class Userdao implements Iuser {


    @Autowired
    private Sessionfactory sessionfactory;< c13/> @Override public
    void Save (user user) {

        //Get session Session Session
        = Sessionfactory.opensession ( );
        Session.begintransaction ();

        Session.save (user);

        Session.gettransaction (). commit ();
        Session.close ();
    }

}

connection pooling to spring management

We know that Hibernate's connection pool support to c3p0 is less than spring, so we can use spring's connection pool. So we load Hibernate's master profile and use spring's database connection pool

That is, part of the configuration is in Hibernate.cfg.xml, and part is configured in the spring file

    <!--data Source configuration-<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > &LT;PR Operty name= "Driverclass" value= "Com.mysql.jdbc.Driver" ></property> <property name= "Jdbcurl" value= "JD
        Bc:mysql:///zhongfucheng "></property> <property name=" user "value=" root "></property> <property name= "Password" value= "root" ></property> <property name= "Initialpoolsize" value= "3" &GT;&L t;/property> <property name= "maxpoolsize" value= "ten" ></property> <property name= "Maxstat Ements "value=" ></property> <property name= "Acquireincrement" value= "2" ></property> & Lt;/bean> <!--load Hibernate's master profile and use spring's database connection pool--<bean id= "Sessionfactory" class= " Org.springframework.orm.hibernate3.LocalSessionFactoryBean "> <!--explains where the profile is located--<property Nam E= "Configlocation" value= "Classpath:hibernate.cfg.xml"/> <property name= "DataSource" ref= "DataSource"/> </bean> 

config file full write "recommended" in spring

Part of us is the main configuration file that loads hibernate, part of the database connection pool that uses spring configuration files ... This is not good ... We should manage the same in spring.

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:x
       Si= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" 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 "> <!--Data Source configuration-<bean id=" DataSource "class=" Com.mchange.v2.c3p0.ComboPooledData Source "> <property name=" driverclass "value=" Com.mysql.jdbc.Driver "></property> <propert Y name= "Jdbcurl" value= "Jdbc:mysql:///zhongfucheng" ></property> <property name= "user" value= "root" > </property> <property name= "password" value= "root" ></property> <property name= "Initia
        Lpoolsize "value=" 3 "></property><property name= "maxpoolsize" value= "></property> <property name=" maxstatements "value=" >& " lt;/property> <property name= "Acquireincrement" value= "2" ></property> </bean> <!
    --All configuration information is done in spring. --<bean id= "sessionfactory" class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean" > &L T;property name= "DataSource" ref= "DataSource"/> <!--Hibernate Common Configuration Properties--<property name= "Hiber Nateproperties "> <props> <prop key=" Hibernate.dialect ">org.hibernate.dialect.my sqldialect</prop> <prop key= "hibernate.show_sql" >true</prop> <prop ke Y= "Hibernate.hbm2ddl.auto" >update</prop> </props> </property> <!--Hib Ernate load Map file, map to Folder-<!--<property name= "Mappingdirectorylocations" > <list> <value>bb</value> </list> </property>--> &lt ;!
                --hibernate load Map file, map to specific location-<property name= "Mappinglocations" > <list> <value>bb/User.hbm.xml</value> </list> </property> </bean> &lt ; Context:component-scan base-package= "BB"/> </beans>

We recommend that you use this one, and you can reduce the configuration file for hibernate. and easily unified management.

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.