1 在spring中支持编程式事物和声明式事务管理,通常使用声明式事物管理,声明式的事物管理是基于aop机制实现的使用很方便。
2 spring支持单一数据库资源的事物管理和跨越多个数据库资源的事物管理既JTA全局事物。
3 在spring中提供了多个事物管理类,常用的是;DataSourceTransactionManager,HibernateTransactionManager和JtaTransactionManager。
DataSourceTransactionManager :数据源事物管理器,用于JDBC框架和MyBatis的事物管理。
HibernateTransactionManager: hibernate事物管理器,用于hibernate事物管理。
JtaTransactionManager:分布式事物管理,把事物管理委托给JAVAEE服务器事物管理器。
4 HibernateTransactionManager加注解的形式进行事物管理:
dao层为日志dao的接口加实现和用户接口加实现,:
package com.dao; import com.entity.Slog; public interface LogDao { public void save(Slog log); }
package com.dao; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.entity.Slog; @Repository(value="logDao") public class LogDaoImpl implements LogDao { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } @Resource public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public void save(Slog log) { try { Session session=sessionFactory.getCurrentSession(); session.save(log); System.out.println("log:ok"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.dao; import com.entity.Student; public interface UserDao { public void save(Student student); }
package com.dao; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.entity.Student; @Repository(value="userDao") public class UserDaoImpl implements UserDao{ private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } @Resource public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void save(Student student){ try { Session session=sessionFactory.getCurrentSession(); session.save(student); System.out.println("student:ok"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
service层,用户的service接口加实现:
package com.service; import com.entity.Student; public interface UserService { public void save(Student student); }
package com.service; import java.util.Date; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.dao.LogDao; import com.dao.UserDao; import com.entity.Slog; import com.entity.Student; @Service(value="userService") public class UserServiceImpl implements UserService{ private UserDao userDao; private LogDao logDao; public LogDao getLogDao() { return logDao; } @Resource public void setLogDao(LogDao logDao) { this.logDao = logDao; } public UserDao getUserDao() { return userDao; } @Resource public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Transactional(propagation=Propagation.REQUIRED) @Override public void save(Student student) { userDao.save(student); Slog sl=new Slog(); sl.setLogDate(new Date()); logDao.save(sl); } }
实体类:
package com.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Slog { @Id @GeneratedValue private Integer logId; private Date logDate; public Integer getLogId() { return logId; } public void setLogId(Integer logId) { this.logId = logId; } public Date getLogDate() { return logDate; } public void setLogDate(Date logDate) { this.logDate = logDate; } }
package com.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Student { @Id @GeneratedValue private Integer studentId; private String studentName; public Integer getStudentId() { return studentId; } public void setStudentId(Integer studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } }
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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.*" /> <context:annotation-config /> <tx:annotation-driven transaction-manager="txManager"/> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:c3p0.properties</value> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="annotatedClasses"> <list> <value>com.entity.Student</value> <value>com.entity.Slog</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
测试类:
package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.entity.Student; import com.service.UserService; public class Test { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); UserService uc=(UserService) ac.getBean("userService"); Student s=new Student(); s.setStudentName("hh"); uc.save(s); } }
5 在dao里获取session的时候,这里需要sessionFactory.getCurrentSession(),要使用上下文里的同一个session;
6 @Transactional,放在哪个方法之上对哪个方法加事物,放在类的上面,对所有方法加事物。
7 @Transactionnal(propagation=Propagation.REQUIRED)里面可以设置事物的属性:
propagation指定事物的传播特性,7个传播特性如下:
1 Propagation.REQUIRED 如果当前环境存在一个事物,则加入当前事物,不存在,则开启一个新的事物。这是默认的特性,也是经常用的。
2 Propagation.SUPPORTS 如果当前环境存在一个事物,则加入当前事物,不存在,则以非事物方式运行。
3 Propagation.REQUIRES_NEW 如果当前环境存在一个事物,让当前的事物挂起(暂停执行),自己再开启一个新的事物,当新的事物执行完毕,原来的事物才会继续执行。如果当前环境不存在事物,同样也是自己开启一个新的事物。
4 Propagation.NOT_SUPPORTED 如果当前环境存在一个事物,让当前事物挂起,自己非事物方式运行,当自己执行完毕,之前的事物继续执行。如果当前环境不存在事物,自己同样直接非事物方式运行。
5 Propagation.NEVER 绝对不能在事物范围内执行,入果在某个事物范围内执行,容器会抛出异常。只有没有关联到事物才会正常执行。
6 Propagation.NESTED 如果当前环境存在一个事物,运行在这个嵌套的事物中,如果当前没有事物就新建一个事物。与父事物相互独立,这个事物有多个回滚的保证点,自己事物的回滚不会对外部事物造成影响。只对DataSourceTransactionManager事物管理器起作用。
7 Propagation.MANDATORY 当前的方法必须加入当前的事物,如果当前不存在事物则抛出异常。
8 @Transactionnal(readOnly=true)设置只读,只是用于查询,会创建只读的connection,这样可以提高查询效率。
9 @Transactional(timeout=50) 事物超时时间,以秒为单位。
10 @Transactional() 通过 isolation 指定事物的隔离级别。
11 @Transactional()只能用于public 修饰的方法上,非public方法将会使得事物失效。
12 通过xml配置事物:
1 配置事物管理器
2 设置事物管理器属性
3 将设置好的属性通过aop切入对应service层
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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.*" /> <context:annotation-config /> <!-- <tx:annotation-driven transaction-manager="txManager"/> --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:c3p0.properties</value> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="annotatedClasses"> <list> <value>com.entity.Student</value> <value>com.entity.Slog</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="save*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="fooServiceOperation" expression="execution(public * com.service..*.save(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/> </aop:config> </beans>