菜鸟学习Spring——60s学会Spring与Hibernate的集成

一、概述。
        Spring与Hibernate的集成在企业应用中是很常用的做法通过Spring和Hibernate的结合能提高我们代码的灵活性和开发效率,下面我就一步一步的给大家讲述Spring如何和Hibernate集成的。
二、代码演示。
导入Hibernate的jar包
Hibernate-3.2/lib/*.jar
Hibernate-3.2/hibernate3.jar
还有导入Spring的相关jar包
我用的数据库是MySql所以要导入MySql的驱动jar包:
mysql-connector-java-3.1.13-bin.jar

目录结构:


Hibernate的实体映射:

Log.java

	package com.tgb.usermgr.domain;
	
	import java.util.Date;
	
	
	
	public class Log {
	
		private int id;
		
		private String type;
		
		private String detail;
		
		private Date time;
	
		public int getId() {
			return id;
		}
	
		public void setId(int id) {
			this.id = id;
		}
	
		public String getType() {
			return type;
		}
	
		public void setType(String type) {
			this.type = type;
		}
	
		public String getDetail() {
			return detail;
		}
	
		public void setDetail(String detail) {
			this.detail = detail;
		}
	
		public Date getTime() {
			return time;
		}
	
		public void setTime(Date time) {
			this.time = time;
		}
		
	}


User.java

	package com.tgb.usermgr.domain;
	
	public class User {
	
		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;
		}
		
	}


Log.hbm.xml

	<?xml version="1.0"?>
	<!DOCTYPE hibernate-mapping PUBLIC 
		"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
	<hibernate-mapping>
		<class name="com.tgb.usermgr.domain.Log" table="t_log">
			<id name="id">
				<generator class="native"/>
			</id>
			<property name="type"/>
			<property name="detail"/>
			<property name="time"/>
		</class>
	</hibernate-mapping>


User.hbm.xml

	<?xml version="1.0"?>
	<!DOCTYPE hibernate-mapping PUBLIC 
		"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
	<hibernate-mapping>
		<class name="com.tgb.usermgr.domain.User" table="t_user">
			<id name="id">
				<generator class="native"/>
			</id>
			<property name="name"/>
		</class>
	</hibernate-mapping>


Hibernate的工具类

HibernateUtils.java

	package com.tgb.usermgr.util;
	
	import org.hibernate.Session;
	import org.hibernate.SessionFactory;
	import org.hibernate.cfg.Configuration;
	
	public class HibernateUtils {
	
		private static SessionFactory factory;
		
		private HibernateUtils() {
		}
		
		static {
			try {
				Configuration cfg = new Configuration().configure();
				factory = cfg.buildSessionFactory();
			}catch(Exception e) {
				e.printStackTrace();
				throw new java.lang.RuntimeException(e);
			}	
		}
		
		public static SessionFactory getSessionFactory() {
			return factory;
		}
		
		public static Session getSession() {
			return factory.openSession();
		}
		
		public static void closeSession(Session session) {
			if (session != null) {
				if (session.isOpen()) {
					session.close();
				}
			}
		}
	}
	


业务逻辑实现和接口:

LogManager.java

	package com.tgb.usermgr.manager;
	
	import com.tgb.usermgr.domain.Log;
	
	public interface LogManager {
	
		public void addLog(Log log);
	}


LogManagerImpl.java

	package com.tgb.usermgr.manager;
	
	import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
	
	import com.tgb.usermgr.domain.Log;
	import com.tgb.usermgr.util.HibernateUtils;
	
	public class LogManagerImpl extends HibernateDaoSupport implements LogManager {
	
		public void addLog(Log log) {
			//getSession().save(log);
			getHibernateTemplate().save(log);
		}
	
	}


UserManager.java

	package com.tgb.usermgr.manager;
	
	import com.tgb.usermgr.domain.User;
	
	public interface UserManager {
	
		public void addUser(User user) throws Exception;
		
	}


UserManagerImpl.java

	package com.tgb.usermgr.manager;
	
	
	
	import java.util.Date;
	
	import org.hibernate.Session;
	import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
	
	import com.tgb.usermgr.domain.Log;
	import com.tgb.usermgr.domain.User;
	import com.tgb.usermgr.util.HibernateUtils;
	
	public class UserManagerImpl extends HibernateDaoSupport implements UserManager {
	
		private LogManager logManager; 
		
	
	
		public void addUser(User user) 
		throws Exception {
			//this.getSession().save(user);
			this.getHibernateTemplate().save(user);
		
			Log log = new Log();
			log.setType("操作日志");
			log.setTime(new Date());
			log.setDetail("XXX");
			
			logManager.addLog(log);
			
			throw new Exception();
		}
		
		public void setLogManager(LogManager logManager) {
			this.logManager = logManager;
		}
	
	}


客户端的测试类:

UserManagerImplTest.java

	package com.tgb.usermgr.manager;
	
	import org.springframework.beans.factory.BeanFactory;
	import org.springframework.context.support.ClassPathXmlApplicationContext;
	
	import com.tgb.usermgr.domain.User;
	
	import junit.framework.TestCase;
	
	public class UserManagerImplTest extends TestCase {
	
		public void testAddUser() {
		BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext-*.xml");
			UserManager userManager = (UserManager)factory.getBean("userManager");
			
			User user = new User();
			user.setName("张三");
			try {
				userManager.addUser(user);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	
	}


配置文件:

hibernate.cfg.xml

	<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
	
	<hibernate-configuration>
		<session-factory>
			<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
			<property name="hibernate.connection.url">jdbc:mysql://localhost/spring_hibernate_2</property>
			<property name="hibernate.connection.username">root</property>
			<property name="hibernate.connection.password">root</property>
			<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
			<property name="hibernate.show_sql">true</property>
			<property name="hibernate.hbm2ddl.auto">update</property>
	
			<mapping resource="com/tgb/usermgr/domain/User.hbm.xml"/>
			<mapping resource="com/tgb/usermgr/domain/Log.hbm.xml"/>
		</session-factory>
	</hibernate-configuration>
	


applicationContext-common.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: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-2.0.xsd
	           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
	           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
		<!-- 配置SessionFactory -->
		<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
			<property name="configLocation">
				<value>classpath:hibernate.cfg.xml</value>
			</property>
		</bean>
		
		<!-- 配置事务管理器 -->
		<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
			<property name="sessionFactory">
				<ref bean="sessionFactory"/>			
			</property>
		</bean>
		
		<!-- 那些类那些方法使用事务 -->
		<aop:config>
			<aop:pointcut id="allManagerMethod" expression="execution(* com.tgb.usermgr.manager.*.*(..))"/>
			<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>
		</aop:config>
		
		<!-- 事务的传播特性 -->	
		<tx:advice id="txAdvice" transaction-manager="transactionManager">
			<tx:attributes>
				<tx:method name="add*" propagation="REQUIRED"/>
				<tx:method name="del*" propagation="REQUIRED"/>
				<tx:method name="modify*" propagation="REQUIRED"/>
				<tx:method name="*" propagation="REQUIRED" read-only="true"/>
			</tx:attributes>
		</tx:advice>
	</beans>
	


applicationContext-beans.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: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-2.0.xsd
	           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
	           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
	           
		<bean id="userManager" class="com.tgb.usermgr.manager.UserManagerImpl">
			<property name="sessionFactory" ref="sessionFactory"/>
			<property name="logManager" ref="logManager"/>
		</bean>
		
		<bean id="logManager" class="com.tgb.usermgr.manager.LogManagerImpl">
			<property name="sessionFactory" ref="sessionFactory"/>
		</bean>
	</beans>


效果图:


三、总结。

        Hibernate与Spring的结合使系统变的更加灵活,能应对一定的需求变化。Hibernate解决了我们数据库变换的问题,Spring解决了我们类与类之间变化的问题。不仅让系统变的灵活了而且大大的提高了我们开发人员的开发效率和维护效率。

原文地址:https://www.cnblogs.com/iplus/p/4490366.html