zoukankan      html  css  js  c++  java
  • Spring @Transactional 使用

    Spring @Transactional是Spring提供的一个声明式事务,对代码的侵入性比较小,只需考虑业务逻辑,不需要把事务和业务搞混在一起。

    @Transactional 可以注解在interface和class层面。由于注解在interface上的方法只能通过JDK Dynamic 来代理。注解在class上的方法Spring默认使用cglib来处理代理,但是局限于class中的public方法,对于非public的方法,如果标记了@Transactional也不会报错,但方法事务无效。这时需要引入Aspectj来处理代理这个方法事务。

    Spring事务配置

    一、xml方式

    1.在Spring配置文件引入<tx:>

    <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: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-3.0.xsd
               http://www.springframework.org/schema/aop 
               http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
               http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    2.配置基于注解的声明式事务管理,如果没有使用Hibernate框架,则将class替换成"org.springframework.jdbc.datasource.DataSourceTransactionManager"

    <!-- 配置声明式事务管理器-->  
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory"></property>  
    </bean>  
    <!-- 注解驱动-->  
    <tx:annotation-driven transaction-manager="txManager"/>

    3.在要使用事务管理的类或者方法上增加代码@Transactional,Spring官方团队建议不要在接口使用。在类上使用@Transactional,类中的所有public方法都将使用事务

    @Transactional
    public class Txtest implements TestService { }

    在public方法上使用@Transactional,则该方法使用事务;非public方法使用@Transactional不会报错,但也不会使用事务,相当于“白做”。

    @Transactional
    public List<Object> getAll() {
        return null;
    }

    如果在类上使用@Transactional,但是类中的某个方法不想使用事务,则可以使用

    @Transactional
    public class Txtest implements TestService {   
        
        @Transactional(propagation = Propagation.NOT_SUPPORTED)
        public List<Object> getAll() {
            return null;
        }   
    }

    二、Java Config 方式

    1、启用事务管理

    @EnableTransactionManagement
    @SpringBootApplication
    public class WantuJuxinliApplication {
    
        public static void main(final String[] args) throws Exception {
            SpringApplication.run(WantuJuxinliApplication.class, args);
        }
    }

    2、配置事务管理器 PlatformTransactionManager

    @Configuration
    @MapperScan(basePackages = "com.xxx")
    public class DataSourceConfig {
    
        @Value("${db_driver}")
        private String driver;
    
        @Value("${db_url}")
        private String jdbcUrl;
    
        @Value("${db_username}")
        private String dbUser;
    
        @Value("${db_password}")
        private String dbPassword;
    
        @Bean(initMethod = "init", destroyMethod = "close")
        public DataSource dataSource() {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUrl(jdbcUrl);
            druidDataSource.setDriverClassName(driver);
            druidDataSource.setUsername(dbUser);
            druidDataSource.setPassword(dbPassword);
            druidDataSource.setMaxActive(20);
            druidDataSource.setInitialSize(1);
            druidDataSource.setMaxWait(60000);
            druidDataSource.setMinIdle(1);
            druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
            druidDataSource.setMinEvictableIdleTimeMillis(300000);
            druidDataSource.setValidationQuery("SELECT 'x'");
            druidDataSource.setTestWhileIdle(true);
            druidDataSource.setTestOnBorrow(false);
            druidDataSource.setTestOnReturn(false);
            druidDataSource.setPoolPreparedStatements(true);
            druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
            return druidDataSource;
        }
    
        @Bean
        public PlatformTransactionManager transactionManager() {
            return new DataSourceTransactionManager(dataSource());
        }
    
        @Bean
        public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
            return new TransactionTemplate(transactionManager);
        }
    
        @Bean
        public SqlSessionFactory sqlSessionFactory() throws Exception {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource());
    
            //分页插件
            PageHelper pageHelper = new PageHelper();
            Properties props = new Properties();
            props.setProperty("reasonable", "true");
            props.setProperty("supportMethodsArguments", "true");
            props.setProperty("returnPageInfo", "check");
            props.setProperty("params", "count=countSql");
            pageHelper.setProperties(props);
            sessionFactory.setPlugins(new Interceptor[] { pageHelper });
    
            sessionFactory.setFailFast(true);
            sessionFactory.setMapperLocations(resolver.getResources("classpath:/config/*Mapper.xml"));
            return sessionFactory.getObject();
        }
    }

    3、同xml方式第三点

    --EOF--

  • 相关阅读:
    解决laravel Class 'DoctrineDBALDriverPDOMySqlDriver' not found 错误
    Ubuntu 服务器443端口证书配置
    服务器部署Apache+PHP+MYSQL+Laravel
    git 的常用命令
    Unity 2D 效应器与来回移动的实现
    Html5 Canvas介绍
    基于servlet+filter+反射模拟实现天猫首页的后端
    cleanCode[2]:函数编写的几大规则
    cleanCode[1]:有意义的命名
    学习JavaWeb aop两种配置方式
  • 原文地址:https://www.cnblogs.com/hduwbf/p/7300710.html
Copyright © 2011-2022 走看看