您的位置:首页 > 编程语言 > Java开发

Spring 整合Hibernate 事务代理类解决方案

2008-09-13 21:30 337 查看
myeclipse6.5创建java项目,添加spring+hibernate框架。

hibernate数据库操作时需要使用到事务,spring整合hibernate通过事务代理类的方式解决提交事务的问题,通过配置文件设置,Spring 配置文件 applicationContext.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.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean
">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>

<!-- 声明一个 Hibernate 3 的 事务管理器供代理类自动管理事务用 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<bean id="StudentDAO" class="dao.StudentDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>

DAO 层核心类 dao.StudentDAO.java中增加标注,加入事务注释

/**
* Student 的 DAO 层,加入了事务标注。
*/
@Transactional
public class StudentDAO extends HibernateDaoSupport {

}

测试类

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

StudentDAO dao = (StudentDAO)ctx.getBean("StudentDAO");
Student user = new Student();
user.setUsername("姓名");
user.setPassword("密码");
user.setAge(200);
dao.save(user);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: