前面已經學習瞭如何使用Spring與Struts2進行整合,本博文主要講解如何使用Spring對Hibernate進行整合java
Spring和Hibernate整合的關鍵點:mysql
bean.xmlspring
<?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.xmlsql
<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:///zhongfucheng</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</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">create</property> </session-factory> </hibernate-configuration>
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='" + password + '\'' + '}'; } }
public interface IUser { void save(); }
public class UserDao implements IUser { @Override public void save() { } }
public class UserService { private UserDao userDao; public void save() { userDao.save(); } }
首先,咱們爲userDao、userService使用Spring來建立對象,以及添加對象的依賴關係,看看Spring的環境是否成功數據庫
@Repository public class UserDao implements IUser { @Override public void save() { } }
@Service public class UserService { @Autowired private UserDao userDao; public void save() { userDao.save(); } }
<?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>
public class Test2 { @Test public void test33() { ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml"); UserService userService = (UserService) ac.getBean("userService"); System.out.println(userService); } }
<?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="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>
<mapping resource="bb/User.hbm.xml" />
@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 test33() { ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml"); UserService userService = (UserService) ac.getBean("userService"); userService.save(new User()); } }
Spring與Hibernate整合的關鍵點之一就是使用Spring來建立SessionFactory對象。其中又有三種方式來建立SessionFactory編程
<!-- 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對象了。markdown
@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(); } }
咱們知道Hibernate對C3P0的鏈接池支持度比不上Spring,所以咱們能夠使用Spring的鏈接池。所以咱們加載Hibernate的主配置文件又使用Spring的數據庫鏈接池session
也就是說,一部分配置在hibernate.cfg.xml,一部分配置在Spring文件中app
<!-- 數據源配置 --> <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> <!-- 加載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>
上面咱們一部分是加載Hibernate的主配置文件,一部分是使用Spring配置文件的數據庫鏈接池…這樣很差…咱們應該在Spring中對其進行同一的管理!ide
<?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"> <!-- 數據源配置 --> <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> <!-- 全部的配置信息都在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="mappingDirectoryLocations"> <list> <value>bb</value> </list> </property>--> <!--Hibernate加載映射文件,映射到具體位置--> <property name="mappingLocations"> <list> <value>bb/User.hbm.xml</value> </list> </property> </bean> <context:component-scan base-package="bb"/> </beans>
咱們推薦的就是使用這一種,就能夠少了Hibernate的配置文件了。而且容易統一管理。
到目前爲止,咱們是使用Hibernate編程式事務控制管理,Spring與Hibernate整合另外一個關鍵就是使用Spring對Hibernate進行事務管理
<!--配置Hibernate的事務管理器類--> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <!--引用的是SessionFactory,SessionFactory包括了數據鏈接池--> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!--開啓以註解的方式來管理事務--> <tx:annotation-driven transaction-manager="txManager"/>
值得注意的是:Spring與Hibernate整合,Spring只支持線程的Session,而且不用咱們手動配置
userDao
@Repository public class UserDao implements IUser { @Autowired private SessionFactory sessionFactory; @Override public void save(User user) { sessionFactory.getCurrentSession().save(user); } }
userService添加@Transactional註解就是爲Hibernate添加了事務管理了。
@Service @Transactional public class UserService { @Autowired private UserDao userDao; public void save(User user) { userDao.save(user); } }