Spring和Hibernate整合

Java框架

浏览数:117

2019-6-29

AD:资源代下载服务

SH整合步骤:

         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                      【事务相关】

         2)配置

                   hibernate.cfg.xml

                   bean.xml

相关实现

(1)实体类和映射文件

public class Dept {
	private int id;
	private String name;
	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;
	}
	
}

 Dept.hbm.xml

<?xml version="1.0"?>
<!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.gqx.entity">

	<class name="Dept"  table="t_Dept">
		<id name="id" column="deptId">
			<generator class="native"></generator>
		</id>
		<property name="name" length="20" column="deptName"></property>
	</class>
</hibernate-mapping>

 (2)Dao

按照传统的Hibernate,以前是这么写的

public class DeptDao_init {
	
	private static SessionFactory sessionFactory;
	static{
		sessionFactory=new Configuration().configure().buildSessionFactory();
	}
	
	public void save(Dept dept){
		//创建管理类对象,创建sessionfatory、创建session,执行操作,关闭
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		session.save(dept);
		session.getTransaction().commit();
		session.close();
	}
}

现在利用spring来注入对象

package com.gqx.dao;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import com.gqx.entity.Dept;

public class DeptDao {
	//Spring 和 Hibernate整合:IOC容器注入
	private SessionFactory sessionFactory;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	//事物管理交给spring
	public void save(Dept dept){
		sessionFactory.getCurrentSession().save(dept);
	}
}

 (3)、service

public class DeptService {
	private DeptDao deptDao;
	public void setDeptDao(DeptDao deptDao) {
		this.deptDao = deptDao;
	}
	
	public void save(Dept dept){
		deptDao.save(dept);
	}
}

 (4)配置文件

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
		<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;DataBaseName=Test</property>
		<property name="hibernate.connection.username">sa</property>
		<property name="hibernate.connection.password">123456</property>
		<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
		
		<!-- 常规配置 -->
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		<!-- 本地jdbc事务配置,你通过getCurrentSession创建的session会绑定到当前线程 -->
		<!-- <property name="hibernate.current_session_context_class">thread</property> -->
		<!-- 2.3 自动建表  -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- 映射 -->
		<mapping resource="com/gqx/entity/Dept.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

 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" xmlns:p="http://www.springframework.org/schema/p"
	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/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
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
     	 http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!-- dao实例 -->
	<bean id="deptDao" class="com.gqx.dao.DeptDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- service实例 -->
	<bean id="deptService" class="com.gqx.service.DeptService">
		<property name="deptDao" ref="deptDao"></property>
	</bean>

	<!-- ########0####Spring和Hibernate整合################ -->
	<!-- 方式一:直接加载hibernate.cfg.xml文件的方式整合 -->
	<!-- SessionFactory类是接口,而注入的必须是实现类,所以要用LocalSessionFactoryBean -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation" value="hibernate.cfg.xml"></property>
	</bean>


	<!-- 事物配置 -->
	<!-- a、配置事物管理器类 Spring声明式事务管理器类: Jdbc技术:DataSourceTransactionManager Hibernate技术:HibernateTransactionManager -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- b、配置事物增强(拦截方法后如何管理事物) -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="*" read-only="false" />
		</tx:attributes>
	</tx:advice>
	<!-- c、aop配置 -->
	<aop:config>
		<aop:pointcut expression="execution(* com.gqx.service.DeptService.*(..))" id="pc" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pc" />
	</aop:config>
</beans>
     

(5)测试类

public class App {
	//容器
	private ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
	@Test
	public void test() throws Exception {
		DeptService service=(DeptService)ac.getBean("deptService");
		System.out.println(service);
		service.save(new Dept());
	}
}

优化

不需要hibernate.cfg.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" xmlns:p="http://www.springframework.org/schema/p"
	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/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
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
     	 http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!-- dao实例 -->
	<bean id="deptDao" class="com.gqx.dao.DeptDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- service实例 -->
	<bean id="deptService" class="com.gqx.service.DeptService">
		<property name="deptDao" ref="deptDao"></property>
	</bean>
	
	<!-- 数据源配置 :C3p0连接池-->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>
		<property name="jdbcUrl" value="jdbc:sqlserver://localhost:1433;DataBaseName=Test"></property>
		<property name="user" value="sa"></property>
		<property name="password" value="123456"></property>
		<property name="initialPoolSize" value="3"></property>
		<property name="maxPoolSize" value="11"></property>
		<property name="maxStatements" value="50"></property>
		<property name="acquireIncrement" value="2"></property>
	</bean>
	
	<!-- ########0####Spring和Hibernate整合################ -->
	<!-- 【推荐】方式(3)所有的配置全部都在Spring配置文件中完成 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		
		<!-- hibernate常用配置 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		
		<!-- hibernate映射配置  -->
		<property name="mappingLocations">
			<list>
				<!-- <value>classpath:com/gqx/entity/Dept.hbm.xml</value> -->
				<value>classpath:com/gqx/entity/*.hbm.xml</value>
			</list>
		</property>
	</bean>
	
	<!-- 事物配置 -->
	<!-- a、配置事物管理器类 
		Spring声明式事务管理器类:
		Jdbc技术:DataSourceTransactionManager
		Hibernate技术:HibernateTransactionManager
	-->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- b、配置事物增强(拦截方法后如何管理事物) -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="*" read-only="false"/>
		</tx:attributes>
	</tx:advice>
	<!-- c、aop配置 -->
	<aop:config>
		<aop:pointcut expression="execution(* com.gqx.service.DeptService.*(..))" id="pc"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/>
	</aop:config>
</beans>
     

 

作者:一盏淡酒、醉了夕阳