菜鸟学习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

  1. package com.tgb.usermgr.domain;  
  2.   
  3. import java.util.Date;  
  4.   
  5.   
  6.   
  7. public class Log {  
  8.   
  9.     private int id;  
  10.       
  11.     private String type;  
  12.       
  13.     private String detail;  
  14.       
  15.     private Date time;  
  16.   
  17.     public int getId() {  
  18.         return id;  
  19.     }  
  20.   
  21.     public void setId(int id) {  
  22.         this.id = id;  
  23.     }  
  24.   
  25.     public String getType() {  
  26.         return type;  
  27.     }  
  28.   
  29.     public void setType(String type) {  
  30.         this.type = type;  
  31.     }  
  32.   
  33.     public String getDetail() {  
  34.         return detail;  
  35.     }  
  36.   
  37.     public void setDetail(String detail) {  
  38.         this.detail = detail;  
  39.     }  
  40.   
  41.     public Date getTime() {  
  42.         return time;  
  43.     }  
  44.   
  45.     public void setTime(Date time) {  
  46.         this.time = time;  
  47.     }  
  48.       
  49. }  
	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

  1. package com.tgb.usermgr.domain;  
  2.   
  3. public class User {  
  4.   
  5.     private int id;  
  6.       
  7.     private String name;  
  8.   
  9.     public int getId() {  
  10.         return id;  
  11.     }  
  12.   
  13.     public void setId(int id) {  
  14.         this.id = id;  
  15.     }  
  16.   
  17.     public String getName() {  
  18.         return name;  
  19.     }  
  20.   
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.       
  25. }  
	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

  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC   
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.     <class name="com.tgb.usermgr.domain.Log" table="t_log">  
  7.         <id name="id">  
  8.             <generator class="native"/>  
  9.         </id>  
  10.         <property name="type"/>  
  11.         <property name="detail"/>  
  12.         <property name="time"/>  
  13.     </class>  
  14. </hibernate-mapping>  
	<?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

  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC   
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.     <class name="com.tgb.usermgr.domain.User" table="t_user">  
  7.         <id name="id">  
  8.             <generator class="native"/>  
  9.         </id>  
  10.         <property name="name"/>  
  11.     </class>  
  12. </hibernate-mapping>  
	<?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

  1. package com.tgb.usermgr.util;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.Configuration;  
  6.   
  7. public class HibernateUtils {  
  8.   
  9.     private static SessionFactory factory;  
  10.       
  11.     private HibernateUtils() {  
  12.     }  
  13.       
  14.     static {  
  15.         try {  
  16.             Configuration cfg = new Configuration().configure();  
  17.             factory = cfg.buildSessionFactory();  
  18.         }catch(Exception e) {  
  19.             e.printStackTrace();  
  20.             throw new java.lang.RuntimeException(e);  
  21.         }     
  22.     }  
  23.       
  24.     public static SessionFactory getSessionFactory() {  
  25.         return factory;  
  26.     }  
  27.       
  28.     public static Session getSession() {  
  29.         return factory.openSession();  
  30.     }  
  31.       
  32.     public static void closeSession(Session session) {  
  33.         if (session != null) {  
  34.             if (session.isOpen()) {  
  35.                 session.close();  
  36.             }  
  37.         }  
  38.     }  
  39. }  
	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

  1. package com.tgb.usermgr.manager;  
  2.   
  3. import com.tgb.usermgr.domain.Log;  
  4.   
  5. public interface LogManager {  
  6.   
  7.     public void addLog(Log log);  
  8. }  
	package com.tgb.usermgr.manager;
	
	import com.tgb.usermgr.domain.Log;
	
	public interface LogManager {
	
		public void addLog(Log log);
	}


LogManagerImpl.java

  1. package com.tgb.usermgr.manager;  
  2.   
  3. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  4.   
  5. import com.tgb.usermgr.domain.Log;  
  6. import com.tgb.usermgr.util.HibernateUtils;  
  7.   
  8. public class LogManagerImpl extends HibernateDaoSupport implements LogManager {  
  9.   
  10.     public void addLog(Log log) {  
  11.         //getSession().save(log);  
  12.         getHibernateTemplate().save(log);  
  13.     }  
  14.   
  15. }  
	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

  1. package com.tgb.usermgr.manager;  
  2.   
  3. import com.tgb.usermgr.domain.User;  
  4.   
  5. public interface UserManager {  
  6.   
  7.     public void addUser(User user) throws Exception;  
  8.       
  9. }  
	package com.tgb.usermgr.manager;
	
	import com.tgb.usermgr.domain.User;
	
	public interface UserManager {
	
		public void addUser(User user) throws Exception;
		
	}


UserManagerImpl.java

  1. package com.tgb.usermgr.manager;  
  2.   
  3.   
  4.   
  5. import java.util.Date;  
  6.   
  7. import org.hibernate.Session;  
  8. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  9.   
  10. import com.tgb.usermgr.domain.Log;  
  11. import com.tgb.usermgr.domain.User;  
  12. import com.tgb.usermgr.util.HibernateUtils;  
  13.   
  14. public class UserManagerImpl extends HibernateDaoSupport implements UserManager {  
  15.   
  16.     private LogManager logManager;   
  17.       
  18.   
  19.   
  20.     public void addUser(User user)   
  21.     throws Exception {  
  22.         //this.getSession().save(user);  
  23.         this.getHibernateTemplate().save(user);  
  24.       
  25.         Log log = new Log();  
  26.         log.setType("操作日志");  
  27.         log.setTime(new Date());  
  28.         log.setDetail("XXX");  
  29.           
  30.         logManager.addLog(log);  
  31.           
  32.         throw new Exception();  
  33.     }  
  34.       
  35.     public void setLogManager(LogManager logManager) {  
  36.         this.logManager = logManager;  
  37.     }  
  38.   
  39. }  
	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

  1. package com.tgb.usermgr.manager;  
  2.   
  3. import org.springframework.beans.factory.BeanFactory;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. import com.tgb.usermgr.domain.User;  
  7.   
  8. import junit.framework.TestCase;  
  9.   
  10. public class UserManagerImplTest extends TestCase {  
  11.   
  12.     public void testAddUser() {  
  13.     BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext-*.xml");  
  14.         UserManager userManager = (UserManager)factory.getBean("userManager");  
  15.           
  16.         User user = new User();  
  17.         user.setName("张三");  
  18.         try {  
  19.             userManager.addUser(user);  
  20.         } catch (Exception e) {  
  21.             // TODO Auto-generated catch block  
  22.             e.printStackTrace();  
  23.         }  
  24.           
  25.     }  
  26.   
  27. }  
	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

  1. <!DOCTYPE hibernate-configuration PUBLIC  
  2.     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  3.     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  4.   
  5. <hibernate-configuration>  
  6.     <session-factory>  
  7.         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
  8.         <property name="hibernate.connection.url">jdbc:mysql://localhost/spring_hibernate_2</property>  
  9.         <property name="hibernate.connection.username">root</property>  
  10.         <property name="hibernate.connection.password">root</property>  
  11.         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
  12.         <property name="hibernate.show_sql">true</property>  
  13.         <property name="hibernate.hbm2ddl.auto">update</property>  
  14.   
  15.         <mapping resource="com/tgb/usermgr/domain/User.hbm.xml"/>  
  16.         <mapping resource="com/tgb/usermgr/domain/Log.hbm.xml"/>  
  17.     </session-factory>  
  18. </hibernate-configuration>  
	<!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

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.          xmlns:aop="http://www.springframework.org/schema/aop"  
  6.          xmlns:tx="http://www.springframework.org/schema/tx"  
  7.          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  8.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
  9.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">  
  10.     <!-- 配置SessionFactory -->  
  11.     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  12.         <property name="configLocation">  
  13.             <value>classpath:hibernate.cfg.xml</value>  
  14.         </property>  
  15.     </bean>  
  16.       
  17.     <!-- 配置事务管理器 -->  
  18.     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  19.         <property name="sessionFactory">  
  20.             <ref bean="sessionFactory"/>            
  21.         </property>  
  22.     </bean>  
  23.       
  24.     <!-- 那些类那些方法使用事务 -->  
  25.     <aop:config>  
  26.         <aop:pointcut id="allManagerMethod" expression="execution(* com.tgb.usermgr.manager.*.*(..))"/>  
  27.         <aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>  
  28.     </aop:config>  
  29.       
  30.     <!-- 事务的传播特性 -->    
  31.     <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  32.         <tx:attributes>  
  33.             <tx:method name="add*" propagation="REQUIRED"/>  
  34.             <tx:method name="del*" propagation="REQUIRED"/>  
  35.             <tx:method name="modify*" propagation="REQUIRED"/>  
  36.             <tx:method name="*" propagation="REQUIRED" read-only="true"/>  
  37.         </tx:attributes>  
  38.     </tx:advice>  
  39. </beans>  
	<?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

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.          xmlns:aop="http://www.springframework.org/schema/aop"  
  6.          xmlns:tx="http://www.springframework.org/schema/tx"  
  7.          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  8.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
  9.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">  
  10.              
  11.     <bean id="userManager" class="com.tgb.usermgr.manager.UserManagerImpl">  
  12.         <property name="sessionFactory" ref="sessionFactory"/>  
  13.         <property name="logManager" ref="logManager"/>  
  14.     </bean>  
  15.       
  16.     <bean id="logManager" class="com.tgb.usermgr.manager.LogManagerImpl">  
  17.         <property name="sessionFactory" ref="sessionFactory"/>  
  18.     </bean>  
  19. </beans>  
	<?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解决了我们类与类之间变化的问题。不仅让系统变的灵活了而且大大的提高了我们开发人员的开发效率和维护效率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值