事物配置样例与解析

来源:互联网 发布:php开发工程师是什么 编辑:程序博客网 时间:2024/05/16 01:40

1 在spring中支持编程式事物和声明式事务管理,通常使用声明式事物管理,声明式的事物管理是基于aop机制实现的使用很方便。

2 spring支持单一数据库资源的事物管理和跨越多个数据库资源的事物管理既JTA全局事物。

3 在spring中提供了多个事物管理类,常用的是;DataSourceTransactionManager,HibernateTransactionManager和JtaTransactionManager。

               DataSourceTransactionManager :数据源事物管理器,用于JDBC框架和MyBatis的事物管理。

               HibernateTransactionManager: hibernate事物管理器,用于hibernate事物管理。

               JtaTransactionManager:分布式事物管理,把事物管理委托给JAVAEE服务器事物管理器。

4 HibernateTransactionManager加注解的形式进行事物管理:

dao层为日志dao的接口加实现和用户接口加实现,:

[java] view plain copy
 print?
  1. package com.dao;  
  2.   
  3. import com.entity.Slog;  
  4.   
  5. public interface LogDao {  
  6.     public void save(Slog log);  
  7. }  
[java] view plain copy
 print?
  1. package com.dao;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.hibernate.Session;  
  6. import org.hibernate.SessionFactory;  
  7. import org.springframework.stereotype.Repository;  
  8.   
  9. import com.entity.Slog;  
  10. @Repository(value="logDao")  
  11. public class LogDaoImpl implements LogDao {  
  12. private SessionFactory sessionFactory;  
  13.       
  14.       
  15.     public SessionFactory getSessionFactory() {  
  16.         return sessionFactory;  
  17.     }  
  18.   
  19.     @Resource  
  20.     public void setSessionFactory(SessionFactory sessionFactory) {  
  21.         this.sessionFactory = sessionFactory;  
  22.     }  
  23.     @Override  
  24.     public void save(Slog log) {  
  25.         try {             
  26.             Session session=sessionFactory.getCurrentSession();               
  27.             session.save(log);  
  28.             System.out.println("log:ok");  
  29.         } catch (Exception e) {  
  30.             // TODO Auto-generated catch block  
  31.             e.printStackTrace();  
  32.         }  
  33.   
  34.     }  
  35.   
  36. }  


[java] view plain copy
 print?
  1. package com.dao;  
  2.   
  3. import com.entity.Student;  
  4.   
  5. public interface UserDao {  
  6.     public void save(Student student);  
  7. }  

[java] view plain copy
 print?
  1. package com.dao;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.hibernate.Session;  
  6. import org.hibernate.SessionFactory;  
  7. import org.springframework.stereotype.Repository;  
  8.   
  9. import com.entity.Student;  
  10. @Repository(value="userDao")  
  11. public class UserDaoImpl implements UserDao{      
  12.     private SessionFactory sessionFactory;  
  13.       
  14.       
  15.     public SessionFactory getSessionFactory() {  
  16.         return sessionFactory;  
  17.     }  
  18.   
  19.     @Resource  
  20.     public void setSessionFactory(SessionFactory sessionFactory) {  
  21.         this.sessionFactory = sessionFactory;  
  22.     }  
  23.   
  24.   
  25.     public void save(Student student){  
  26.         try {             
  27.             Session session=sessionFactory.getCurrentSession();  
  28.               
  29.             session.save(student);        
  30.               
  31.             System.out.println("student:ok");  
  32.         } catch (Exception e) {  
  33.             // TODO Auto-generated catch block  
  34.             e.printStackTrace();  
  35.         }  
  36.           
  37.           
  38.     }  
  39. }  

service层,用户的service接口加实现:

[java] view plain copy
 print?
  1. package com.service;  
  2.   
  3. import com.entity.Student;  
  4.   
  5. public interface UserService {  
  6.     public void save(Student student);  
  7. }  

[java] view plain copy
 print?
  1. package com.service;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.springframework.stereotype.Service;  
  8. import org.springframework.transaction.annotation.Propagation;  
  9. import org.springframework.transaction.annotation.Transactional;  
  10.   
  11. import com.dao.LogDao;  
  12. import com.dao.UserDao;  
  13. import com.entity.Slog;  
  14. import com.entity.Student;  
  15. @Service(value="userService")  
  16. public class UserServiceImpl implements UserService{      
  17.     private UserDao userDao;  
  18.     private LogDao logDao;  
  19.       
  20.       
  21.     public LogDao getLogDao() {  
  22.         return logDao;  
  23.     }  
  24.     @Resource  
  25.     public void setLogDao(LogDao logDao) {  
  26.         this.logDao = logDao;  
  27.     }  
  28.     public UserDao getUserDao() {  
  29.         return userDao;  
  30.     }  
  31.     @Resource  
  32.     public void setUserDao(UserDao userDao) {  
  33.         this.userDao = userDao;  
  34.     }  
  35.     @Transactional(propagation=Propagation.REQUIRED)  
  36.     @Override     
  37.     public void save(Student student) {  
  38.         userDao.save(student);  
  39.         Slog sl=new Slog();  
  40.         sl.setLogDate(new Date());  
  41.         logDao.save(sl);  
  42.       
  43.     }  
  44. }  

实体类:

[java] view plain copy
 print?
  1. package com.entity;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import javax.persistence.Entity;  
  6. import javax.persistence.GeneratedValue;  
  7. import javax.persistence.Id;  
  8. @Entity  
  9. public class Slog {  
  10.     @Id  
  11.     @GeneratedValue  
  12.     private Integer logId;  
  13.     private Date logDate;  
  14.     public Integer getLogId() {  
  15.         return logId;  
  16.     }  
  17.     public void setLogId(Integer logId) {  
  18.         this.logId = logId;  
  19.     }  
  20.     public Date getLogDate() {  
  21.         return logDate;  
  22.     }  
  23.     public void setLogDate(Date logDate) {  
  24.         this.logDate = logDate;  
  25.     }  
  26.       
  27.       
  28. }  

[java] view plain copy
 print?
  1. package com.entity;  
  2.   
  3. import javax.persistence.Entity;  
  4. import javax.persistence.GeneratedValue;  
  5. import javax.persistence.Id;  
  6.   
  7. @Entity  
  8. public class Student {  
  9.     @Id  
  10.     @GeneratedValue  
  11.     private Integer studentId;  
  12.     private String studentName;  
  13.     public Integer getStudentId() {  
  14.         return studentId;  
  15.     }  
  16.     public void setStudentId(Integer studentId) {  
  17.         this.studentId = studentId;  
  18.     }  
  19.     public String getStudentName() {  
  20.         return studentName;  
  21.     }  
  22.     public void setStudentName(String studentName) {  
  23.         this.studentName = studentName;  
  24.     }  
  25.       
  26. }  

applicationContext.xml:

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  7.         http://www.springframework.org/schema/aop   
  8.         http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  9.         http://www.springframework.org/schema/tx  
  10.         http://www.springframework.org/schema/tx/spring-tx-2.5.xsd        
  11.         http://www.springframework.org/schema/context  
  12.         http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
  13.     <context:component-scan base-package="com.*" />  
  14.     <context:annotation-config />  
  15.     <tx:annotation-driven transaction-manager="txManager"/>  
  16.     <bean  
  17.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  18.         <property name="locations">  
  19.             <value>classpath:c3p0.properties</value>  
  20.         </property>  
  21.     </bean>  
  22.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
  23.         <property name="driverClass" value="${driverClass}"></property>  
  24.         <property name="jdbcUrl" value="${jdbcUrl}"></property>  
  25.         <property name="user" value="${user}"></property>  
  26.         <property name="password" value="${password}"></property>  
  27.     </bean>  
  28.   
  29.     <bean id="sessionFactory"  
  30.         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  31.         <property name="dataSource" ref="dataSource"></property>  
  32.         <property name="annotatedClasses">  
  33.             <list>  
  34.                 <value>com.entity.Student</value>  
  35.                 <value>com.entity.Slog</value>  
  36.             </list>  
  37.         </property>  
  38.         <property name="hibernateProperties">  
  39.             <props>  
  40.                 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>  
  41.                 <prop key="hibernate.show_sql">true</prop>  
  42.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  43.             </props>  
  44.         </property>  
  45.   
  46.     </bean>  
  47.     <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  48.          <property name="sessionFactory" ref="sessionFactory" />  
  49.     </bean>  
  50. </beans>  

测试类:

[java] view plain copy
 print?
  1. package com.test;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. import com.entity.Student;  
  7. import com.service.UserService;  
  8.   
  9. public class Test {  
  10.   
  11.     public static void main(String[] args) {  
  12.         ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");  
  13.         UserService uc=(UserService) ac.getBean("userService");  
  14.         Student s=new Student();  
  15.         s.setStudentName("hh");  
  16.         uc.save(s);  
  17.           
  18.     }  
  19.   
  20. }  


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

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  7.         http://www.springframework.org/schema/aop   
  8.         http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  9.         http://www.springframework.org/schema/tx  
  10.         http://www.springframework.org/schema/tx/spring-tx-2.5.xsd        
  11.         http://www.springframework.org/schema/context  
  12.         http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
  13.     <context:component-scan base-package="com.*" />   
  14.     <context:annotation-config />   
  15.     <!-- <tx:annotation-driven transaction-manager="txManager"/> -->  
  16.     <bean  
  17.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  18.         <property name="locations">  
  19.             <value>classpath:c3p0.properties</value>  
  20.         </property>  
  21.     </bean>  
  22.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
  23.         <property name="driverClass" value="${driverClass}"></property>  
  24.         <property name="jdbcUrl" value="${jdbcUrl}"></property>  
  25.         <property name="user" value="${user}"></property>  
  26.         <property name="password" value="${password}"></property>  
  27.     </bean>  
  28.   
  29.     <bean id="sessionFactory"  
  30.         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  31.         <property name="dataSource" ref="dataSource"></property>  
  32.         <property name="annotatedClasses">  
  33.             <list>  
  34.                 <value>com.entity.Student</value>  
  35.                 <value>com.entity.Slog</value>  
  36.             </list>  
  37.         </property>  
  38.         <property name="hibernateProperties">  
  39.             <props>  
  40.                 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>  
  41.                 <prop key="hibernate.show_sql">true</prop>  
  42.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  43.             </props>  
  44.         </property>  
  45.   
  46.     </bean>  
  47.       
  48.     <bean id="txManager"  
  49.         class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  50.         <property name="sessionFactory" ref="sessionFactory" />  
  51.     </bean>  
  52.     <tx:advice id="txAdvice" transaction-manager="txManager">  
  53.         <tx:attributes>  
  54.             <tx:method name="get*" read-only="true" />  
  55.             <tx:method name="save*" propagation="REQUIRED"/>  
  56.         </tx:attributes>  
  57.     </tx:advice>  
  58.   <aop:config>  
  59.     <aop:pointcut id="fooServiceOperation" expression="execution(public * com.service..*.save(..))"/>  
  60.     <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>  
  61.   </aop:config>  
  62. </beans>  





0 0
原创粉丝点击