Hibernate——與Spring整合

一、Spring和Hibernate整合步驟

參考:https://mp.weixin.qq.com/s/pIMWtg8t8N-CUtvu-lIqkQ
Spring和Hibernate整合的關鍵點:
——SessionFactory對象交給Spring來創建
——Hibernate的事務交給Spring進行管理

1.1 引入jar包

連接池/數據庫驅動包
Hibernate相關jar
Spring 核心包(5個)
Spring aop 包(4個)
spring-orm-3.2.5.RELEASE.jar 【spring對hibernate的支持】
spring-tx-3.2.5.RELEASE.jar 【事務相關】
在這裏插入圖片描述

1.2 配置文件

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

<hibernate-configuration>
    <!-- 通常,一個session-factory節點代表一個數據庫 -->
    <session-factory>

        <!-- 1. 數據庫連接配置 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>
        <!--數據庫方法配置, hibernate在運行的時候,會根據不同的方言生成符合當前數據庫語法的sql-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- 2. 其他相關配置 -->
        <!-- 2.1 顯示hibernate在運行時候執行的sql語句 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 2.2 格式化sql -->
        <property name="hibernate.format_sql">true</property>
        <!-- 2.3 自動建表  -->
        <property name="hibernate.hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

1.3 搭建配置環境測試

User.java

public class User {
    private String name;
    private String password;
    private int id;
}

IUser.java

public interface IUser {
    void save();
}

UserDao.java

public class UserDao implements IUser {
    @Override
    public void save() {
    }
}

UserService.java

public class UserService {
    private UserDao userDao;
    public void save() {
        userDao.save();
    }
}

1.3.1 測試Spring環境

爲userDao、userService使用Spring來創建對象,以及添加對象的依賴關係,看看Spring的環境是否成功。

創建UserDao實例—>@Repository
UserDao.java

@Repository
public class UserDao implements IUser {
    @Override
    public void save() {
    }
}

創建userService實例,並注入userDao屬性
UserService.java

@Service
public class UserService {
	@Autowired
    private UserDao userDao;
    public void save() {
        userDao.save();
    }
}

在Spring配置文件中使用註解掃描器
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">
	<context:component-scan base-package="com.my"/>
</beans>

測試:成功得到userService對象,並且userService對象含有userDao屬性的值

public class Test {
    @Test
    public void test1() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
        UserService userService = (UserService) ac.getBean("userService");
        System.out.println(userService);
    }
}

1.3.2 測試Hibernate環境

映射配置文件
User.hbm.xml

<?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">
<hibernate-mapping package="com.my.entity">
    <class name="User" table="t_user">
        <id name="id" column="user_id">
            <generator class="native"/>
        </id>
        <property name="name" column="name"/>
        <property name="password" column="password"/>
    </class>
</hibernate-mapping>

主配置文件加載映射文件
Hibernate.cfg.xml

<mapping resource="com/my/entity/User.hbm.xml" />

創建SessionFactory,Session

@Repository
public class UserDao implements IUser {
    @Override
    public void save(User user) {
        //得到SessionFactory
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        //得到Session
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
        session.close();
    }
}

測試

public class Test2 {
    @Test
    public void test2() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
        UserService userService = (UserService) ac.getBean("userService");
        userService.save(new User());
    }
}

二、使用Spring創建SessionFactory對象

2.1 直接加載hibernate主配置文件

bean.xml

<!--
SessionFactory是一個工廠,我們要使用它的實現類
我們使用的是hibernate的3.6版本,因此加載的是3
-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<!--說明配置文件所在的位置-->
	<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>

那麼在userDao中就不用我們自己手動來創建SessionFactory對象了。

@Repository
public class UserDao implements IUser {
    @Autowired
    private SessionFactory sessionFactory;
    @Override
    public void save(User user) {
        //得到Session
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
        session.close();
    }
}

2.2 連接池交給Spring管理

Hibernate對C3P0的連接池支持度比不上Spring,因此可以使用Spring的連接池。因此我們加載Hibernate的主配置文件又使用Spring的數據庫連接池。即一部分配置在hibernate.cfg.xml,一部分配置在Spring文件中。
bean.xml

<!-- 數據源配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="com.mysql.jdbc.Driver"/>
	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8"/>
	<property name="user" value="root"/>
	<property name="password" value="123456"/>
	<property name="initialPoolSize" value="3"/>
	<property name="maxPoolSize" value="10"/>
	<property name="maxStatements" value="100"/>
	<property name="acquireIncrement" value="2"/>
</bean>
<!--加載Hibernate的主配置文件,又使用Spring的數據庫連接池-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<!--說明配置文件所在的位置-->
	<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
	<property name="dataSource" ref="dataSource"/>
</bean>

2.3 配置文件全寫Spring中

推薦
bean.xml

<!-- 數據源配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="com.mysql.jdbc.Driver"/>
	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8"/>
	<property name="user" value="root"/>
	<property name="password" value="123456"/>
	<property name="initialPoolSize" value="3"/>
	<property name="maxPoolSize" value="10"/>
	<property name="maxStatements" value="100"/>
	<property name="acquireIncrement" value="2"/>
</bean>
<!-- 所有的配置信息都在Spring中完成-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<property name="dataSource" ref="dataSource"/>
	<!--Hibernate常用的配置屬性-->
	<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加載映射文件,映射到具體位置-->
	<property name="mappingLocations">
		<list>
			<value>com/my/entity/User.hbm.xml</value>
		</list>
	</property>
</bean>
<!-- 包掃描 -->
<context:component-scan base-package="com.my"/>

三、Spring管理事務

到目前爲止,我們是使用Hibernate編程式事務控制管理,Spring與Hibernate整合另一個關鍵就是使用Spring對Hibernate進行事務管理。
注意:Spring與Hibernate整合,Spring只支持線程的Session,並且不用我們手動配置。

註冊HibernateTransactionManager類:
bean.xml

 <!--配置Hibernate的事務管理器類-->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
	<!--引用的是SessionFactory,SessionFactory包括了數據連接池-->
	<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!--開啓以註解的方式來管理事務-->
<tx:annotation-driven transaction-manager="txManager"/>

UserDao.java

@Repository
public class UserDao implements IUser {
    @Autowired
    private SessionFactory sessionFactory;
    @Override
    public void save(User user) {
        sessionFactory.getCurrentSession().save(user);
    }
}

UserService類添加@Transactional註解就是爲Hibernate添加了事務管理了。
UserService.java

@Service
@Transactional
public class UserService {
    @Autowired
    private UserDao userDao;
    public void save(User user) {
        userDao.save(user);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章