tags: Spring


preface

Now that you’ve learned how to use Spring to integrate with Struts2, this post will focus on how to integrate Hibernate using Spring

Key points of Spring and Hibernate integration:

  • The SessionFactory object is handed to Spring to create
  • Hibernate’s transactions are managed by Spring

Spring and Hibernate integration steps

The introduction of the jar package

  • Connection pool/database driver package
  • Hibernate related jarCopy the code
  • Spring Core package (5)Copy the code
  • Spring AOP Package (4)Copy the code
  • Spring-orm-3.2.5.release.jarCopy the code
  • Spring-tx-3.2.5.release.jar


The configuration file

  •   hibernate.cfg.xml
    Copy the code
  •   bean.xml
    Copy the code

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>
Copy the code

hibernate.cfg.xml


<hibernate-configuration>
    <! A session-factory node represents a database -->
    <session-factory>

        <! -- 1. Database connection configuration -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///zhongfucheng</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <! Hibernate generates SQL in different dialects according to the current database syntax.
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>


        <! -- 2. Other related configurations -->
        <! SQL statements executed by Hibernate at runtime
        <property name="hibernate.show_sql">true</property>
        <! SQL > SQL > SQL >
        <property name="hibernate.format_sql">true</property>
        <! -- 2.3 Automatic table building -->
        <property name="hibernate.hbm2ddl.auto">create</property>

    </session-factory>
</hibernate-configuration>
Copy the code

Set up the configuration environment test

  • User

package bb;

/** * Created by ozc on 2017/5/15. */
public class User {

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

    public int getId(a) {
        return id;
    }

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

    public String getName(a) {
        return name;
    }

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

    public String getPassword(a) {
        return password;
    }

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

    @Override
    public String toString(a) {
        return "User{" +
                "name='" + name + '\' ' +
                ", password='" + password + '\' ' +
                '} '; }}Copy the code
  • IUser interface

public interface IUser {
    void save(a);
}
Copy the code
  • UserDao

public class UserDao implements IUser {

    @Override
    public void save(a) {}}Copy the code
  • userService

public class UserService {
    
    private UserDao userDao;

    public void save(a) { userDao.save(); }}Copy the code

Testing the Spring environment

First, let’s use Spring to create objects for the userDao and userService and add object dependencies to see if the Spring environment is successful

  • Create UserDao instance –> @repository

@Repository
public class UserDao implements IUser {

    @Override
    public void save(a) {}}Copy the code
  • Create the userService instance and inject the userDao attribute


@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public void save(a) { userDao.save(); }}Copy the code
  • Use the annotation 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>
Copy the code
  • Test: The userService object was successfully obtained and the userService object contains the value of the userDao attribute

public class Test2 {

    @Test
    public void test33(a) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");


        UserService userService = (UserService) ac.getBean("userService"); System.out.println(userService); }}Copy the code


Testing the Hibernate environment

  • Mapping configuration file

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

      

<hibernate-mapping package="bb">

	<class name="User" table="t_user">
		<id name="id" column="user_id">
			<generator class="native"></generator>
		</id>
		<property name="name" column="name"></property>
		<property name="password" column="password"></property>
	</class>
</hibernate-mapping>

Copy the code
  • The master profile loads the mapping file

        <mapping resource="bb/User.hbm.xml" />
Copy the code
  • Create SessionFactory, Session

@Repository
public class UserDao implements IUser {

    @Override
    public void save(User user) {

        / / get the SessionFactory
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

        / / get the SessionSession session = sessionFactory.openSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); session.close(); }}Copy the code
  • Testing:

public class Test2 {

    @Test
    public void test33(a) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");


        UserService userService = (UserService) ac.getBean("userService");
        userService.save(newUser()); }}Copy the code


Use Spring to create the SessionFactory object

One of the key points of Spring’s integration with Hibernate is the use of Spring to create SessionFactory objects. There are three ways to create a SessionFactory

Load the Hibernate main configuration file directly


    <! SessionFactory is a factory whose implementation class we are going to use. We are using version 3.6 of Hibernate, so load 3 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        
        <! Specify the location of the configuration file -->
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
    </bean>
Copy the code

We don’t need to manually create the SessionFactory object in the userDao.


@Repository
public class UserDao implements IUser {


    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void save(User user) {

        / / get the SessionSession session = sessionFactory.openSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); session.close(); }}Copy the code


The connection pool is managed by Spring

We know that Hibernate has less connection pooling support for C3P0 than Spring, so we can use Spring’s connection pooling. So we load Hibernate’s main configuration file and use Spring’s database connection pool

That is, part of the configuration is in hibernate.cfg.xml and part is in the Spring file

    <! -- Data source configuration -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///zhongfucheng"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
        <property name="initialPoolSize" value="3"></property>
        <property name="maxPoolSize" value="10"></property>
        <property name="maxStatements" value="100"></property>
        <property name="acquireIncrement" value="2"></property>
    </bean>


    <! Load Hibernate's main configuration file and use Spring's database connection pool
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

        <! Specify the location of the configuration file -->
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
Copy the code


Write all configuration files in Spring.

Above we have part Hibernate main configuration file loaded, part database connection pool using Spring configuration file… It’s not good… We should manage it the same way in Spring!


<?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">


    <! -- Data source configuration -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///zhongfucheng"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
        <property name="initialPoolSize" value="3"></property>
        <property name="maxPoolSize" value="10"></property>
        <property name="maxStatements" value="100"></property>
        <property name="acquireIncrement" value="2"></property>
    </bean>


    <! All configuration information is done in Spring. -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

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

        <! Hibernate configuration properties -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

        <! Hibernate loads the mapping file and maps it to the folder.
<! -- <property name="mappingDirectoryLocations"> <list> <value>bb</value> </list> </property>-->

        <! Hibernate loads the mapping file and maps it to a specific location.
        <property name="mappingLocations">
            <list>
                <value>bb/User.hbm.xml</value>
            </list>
        </property>

    </bean>

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

</beans>
Copy the code

We recommend using this one to eliminate Hibernate configuration files. And easy to unified management.


Spring Management transactions

So far, we have used Hibernate for programmatic transaction control management. Another key to Spring’s integration with Hibernate is to use Spring for Hibernate transaction management

    <! Configure Hibernate transaction manager classes -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

        <! SessionFactory = SessionFactory = SessionFactory = SessionFactory = SessionFactory
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <! Enable annotated transaction management -->
    <tx:annotation-driven transaction-manager="txManager"/>
Copy the code

It’s worth noting that Spring is integrated with Hibernate. Spring only supports sessions for threads, and we don’t have to manually configure them


userDao


@Repository
public class UserDao implements IUser {


    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void save(User user) { sessionFactory.getCurrentSession().save(user); }}Copy the code

UserService adds transaction management to Hibernate by adding the @Transactional annotation.


@Service
@Transactional
public class UserService {

    @Autowired
    private UserDao userDao;

    public void save(User user) { userDao.save(user); }}Copy the code

If you find this article helpful, give the author a little encouragement