三大框架的整合(一)——Spring 和 Hibernate

    1、整合的目的:
            *让 Spring 管理单例的SessionFactory

            *让 Spring 管理事务(采用基于注解的方式)


    2、整合的步骤:

        ·在 applicationContext.xml 中   

			<!-- 配置SessionFactory -->
			<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
				<property name="dataSource" ref="dataSource"></property>
				<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
			</bean>

        ·因为数据库链接配置需要单独修改,所以单独建立文件 jdbc.properties

		jdbcUrl = jdbc:mysql:///test_Demo
		driverClass = com.mysql.jdbc.Driver
		username = root
		password = 1234
        ·同时在 applicationContext.xml 中导入外部文件,同时配置数据库连接池

				<!-- 导入外部的properties配置文件 -->
					<context:property-placeholder location="classpath:jdbc.properties"/>

				<!-- 配置数据库连接池 -->
				<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
					<!-- =========== 数据库连接信息 =========== -->
						<property name="jdbcUrl" value="${jdbcUrl}"></property>
						<property name="driverClass" value="${driverClass}"></property>
						<property name="user" value="${username}"></property>
						<property name="password" value="${password}"></property>
					<!-- =========== 连接池的管理配置 =========== -->
					<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
						<property name="initialPoolSize" value="3"></property>
					<!--连接池中保留的最小连接数。Default: 3 -->
						<property name="minPoolSize" value="3"></property>
					<!--连接池中保留的最大连接数。Default: 15 -->
						<property name="maxPoolSize" value="5"></property>
					<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
						<property name="acquireIncrement" value="3"></property>
					<!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
						<property name="maxStatements" value="8"></property>
					<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
						<property name="maxStatementsPerConnection" value="5"></property>
					<!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
						<property name="maxIdleTime" value="1800"></property>
				</bean>

        ·测试代码,在 test文件夹中

				public  class  TestSpring{					
					private  ApplicationContext  ac = new ClassPathXmlApplication("applicationContext.xml");

					// 测试 SessionFactory 
					@Test
					public  void  testSessionFactory()  throws  Exception{
						SessionFactory  sf = (SessionFactory)ac.getBean("sessionFactory");
						s.o.p(sf.openSession());
					}					
				}
    2、事务管理配置,在applictionContext 中
			<!-- 配置声明式的事务管理(采用基于注解的方式) -->
			<bean  id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
				<property  name="sessionFactory" ref="sessionFactory"></property>
			</bean>
			<tx:annotation-driven  transaction-manager="txManager"/>
        因为加注解的类的实例需要由 Spring 容器管理,才能做 AOP拦截代理,所以创建 TestService.java

			@Service
			public  class  TestService{	
				@Resource
				private  SessionFactory  sessionFactory;

				@Transactional
				public  void  saveToUsers(){
					Session  session  = sessionFactory.getCurrentSession();	// getCurrentSession() 是获取已经做好事务管理的session

					session.save(new  User());
					int  a = 1/0;
					session.save(new User());
				}
			}

        创建 cn.itcast.oa.domain.User.java

				public  class  User{
					private  Long  id;
					封装……
				}
        同包下创建 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 package="cn.google.oa.domain">
					<class name="User" table="demo_user">
						<id name="id">
							<generator class="native"/>
						</id>
					</class>					
				</hibernate-mapping>	
        在 hibernate.cfg.xml 中添加映射文件

				<!-- 声明映射文件 -->
				<mapping resource="cn/google/oa/domain/User.hbm.xml" />

    3、返回 TestSpring.java ,添加方法测试事务管理

			public  class  TestSpring{
				// 测试事务管理
				@Test
				public  void  testTx()  throws  Exception{
					TestService  service  = (TestService)ac.getBean("testService");	// 这里的service 必须从容器里获得,不能 new,否则事务无效
					service.saveToUsers();
				}
			}

    4、测试结果:
            先注释异常代码,执行测试,结果数据库插入1、2两条
            取消注释,执行,报异常
            再注释异常,执行,结果显示1、2、4、5
            ok






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值