Spring集成Hibernate
定义实体类
对象类必须继承HibernateDaoSupport类
为了使用动态代理,将类实现接口
LogManagerImpl:
UserManagerImpl:
继承HibernateDaoSupport类就可以使用hibernateTempate
hibernateTempate:spring创建的session,这个session和当前线程绑定,线程结束时session关闭。它是一个私有的实例全局变量,只能通过继承自对象得方法使用。
配置Spring配置文件
代码示例:
<?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.hibernate5.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- 配置事务的传播特性 -->
<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="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 哪些类的哪些方法参与事务 -->
<aop:config>
<aop:pointcut id="allManagerMethod" expression="execution(* com.bjsxt.usermgr.manager.*.*(..))"/>
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>
</aop:config>
</beans>
- 配置Session工厂bean。创建工厂时创建的工厂不是真正地session工厂,而是工厂的代理,只有使用工厂时,才会创建真正地session工厂。
- 配置事物管理器。通过session工厂管理/创建事物。
- REQUIRED事物传播特性:如果存在一个事务,则支持当前事务,如果没有事务则开启。实现多个方法都使用同一个事物,事物并行。(REQUIRED是默认的事务传播特性)
- 配置aop。将事物的传播特性作为Advise,定义哪些类的哪些方法适用Advise。
PS: 由于Hibernate的配置文件没有特别需要注意的地方,在此不做赘述
应用和异常
代码示例:
package com.bjsxt.usermgr.client;
import com.bjsxt.usermgr.manager.UserManager;
import com.bjsxt.usermgr.model.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) {
User user = new User();
user.setName("zhangsan");
// 创建session工厂
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext-*.xml");
UserManager userManager = (UserManager)factory.getBean("userManager");
try {
userManager.addUser(user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
创建session工厂的过程:
- 创建bean工厂;
- 创建session工厂;
- 通过session工厂生成事务管理器。
使用工厂的方法:
- 事务管理器通过事务的传播特性创建事务;
- 通过AOP确定Jointcut和Pointcut;
- 向方法中织入Advise。
方法执行完毕后由事务管理器自动提交事务。
异常
执行过程中出现异常:
运行异常,事物提交以后会回滚;
编译异常,事物提交以后不会回滚;
说明:本文仅用作学习笔记,无其他用途,如有冒犯可联系本人删除