如何让spring管理hibernate事务机制(annotation)
第一步:在beans.xml中配置:
<bean id=”txManager”>
<property name=”sessionFactory” ref=”sessionFactory” />
</bean>
<!– enable the configuration of transactional behavior based on annotations –>
<tx:annotation-driven transaction-manager=”txManager”/>
第二步:什么方法上需要事务管理,就在该方法的service层上添加注解 @Transactional
@Transactional
public void save(){
tuserdao.save();
}
第三步:创建session 只能为getCurrentSession()
Session session = sessionfactory.getCurrentSession();
![如何让spring管理hibernate事务机制(annotation) 如何让spring管理hibernate事务机制(annotation)]()
全文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:context=”http://www.springframework.org/schema/context”
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/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd“>
<context:annotation-config/> <!– Spring中annotation必须填写 –>
<bean name=”u”>
<!– 下面一行与<context:annotation-config/>后在TuserDAOImpl中写Resource等同 –>
<!–<property name=”sessionfactory” ref=”sessionFactory” /> –>
</bean>
<bean id=”userService”>
<property name=”tuserdao” ref=”u” />
</bean>
<!–利用Spring配备数据库的连接数据源–>
<bean>
<property name=”locations”>
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id=”dataSource” destroy-method=”close”
class=”org.apache.commons.dbcp.BasicDataSource”>
<property name=”driverClassName” value=”${jdbc.driverClassName}”/>
<property name=”url” value=”${jdbc.url}”/>
<property name=”username” value=”${jdbc.username}”/>
<property name=”password” value=”${jdbc.password}”/>
</bean>
<!– Spring整合hibernate给hibernate创建单例sessionFactory,并且利用Spring关联数据库 –>
<bean id=”sessionFactory”>
<property name=”dataSource” ref=”dataSource”/> <!– 让Spring给这个sessionFactory关联上数据库 –>
<property name=”annotatedClasses”> <!– 告诉hibernate哪些类被注解了 –>
<list>
<value>edu.zust.model.Tuser</value>
</list>
</property>
<property name=”hibernateProperties”> <!– 指明hibernate配置属性 –>
<props>
<prop key=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</prop>
<prop key=”hibernate.show_sql”>true</prop>
<prop key=”hibernate.format_sql”>true</prop>
</props>
</property>
</bean>
<!-声明hibernate事务管理–>
<bean id=”txManager”>
<property name=”sessionFactory” ref=”sessionFactory” />
</bean>
<!– enable the configuration of transactional behavior based on annotations –>
<!–指明是用annotation方式–>
<tx:annotation-driven transaction-manager=”txManager”/>
</beans>