spring基于注解和xml声明式事务控制

1.xml

dao

package com.wzk.dao;

import com.wzk.domain.Account;

public interface AccountDao  {

    Account findById(Integer accountId);

    Account findByName(String name);

    void updateAccount(Account account);
}




package com.wzk.dao.impl;

import com.wzk.dao.AccountDao;
import com.wzk.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {



    @Override
    public Account findById(Integer accountId) {
        List<Account> accounts = getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        if(accounts.isEmpty()){
            return null;
        }else{
            return accounts.get(0);
        }
    }

    @Override
    public Account findByName(String name) {
        List<Account> accounts = getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),name);
        if(accounts.isEmpty()){
            return null;
        }else{
            return accounts.get(0);
        }
    }

    @Override
    public void updateAccount(Account account) {
        getJdbcTemplate().update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
}


service

package com.wzk.service;

import com.wzk.domain.Account;

public interface AccountService {

    Account findAccountById(Integer accountId);

    void transfer(String sourceName,String targerName,Float money);
}




package com.wzk.service.impl;

import com.wzk.dao.AccountDao;
import com.wzk.dao.impl.AccountDaoImpl;
import com.wzk.domain.Account;
import com.wzk.service.AccountService;

public class AccountServiceImpl implements AccountService {

    private AccountDaoImpl accountDaoImpl;

    public void setAccountDao(AccountDaoImpl accountDaoImpl) {
        this.accountDaoImpl = accountDaoImpl;
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDaoImpl.findById(accountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        Account source = accountDaoImpl.findByName(sourceName);
        Account target = accountDaoImpl.findByName(targetName);
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        accountDaoImpl.updateAccount(source);
        int i = 1/0;
        accountDaoImpl.updateAccount(target);
    }
}

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

    <bean id="accountService" class="com.wzk.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <bean id="accountDao" class="com.wzk.dao.impl.AccountDaoImpl">
<!--        <property name="template" ref="jdbcTemplate"></property>-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>


    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <!-- spring中基于xml的声明式事务控制配置步骤
            1、配置事务管理器
            2、配置事务的通知
                此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop
                使用tx:advice标签配置事务通知
                    属性:
                        id:给事务通知起唯一一个标识
                        transaction-manager给事务通知提供一个事务管理器引用
             3、配置aop中的通用切入点表达式
             4、建立事务和切入点表达式的对应关系
             5、配置事务的属性
                    是在事务的通知tx:advice标签的内部
     -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置事务的通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置事务的属性
                isolation:用于指定事务的隔离级别,默认值是DEFAULT,表示数据库的默认隔离级别
                propagation:用于指定事务的传播行为,默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方式SUPPORTS
                read-only:用于指定事务是否只读,只有查询方式设置为true。默认值是false,表示读写
                timeout:指定事务的超时时间,默认值是-1,表示永不超时,如果指定了数值,以秒为单位。
                rollback-for:用于指定一个异常,当产生异常时,事务回滚,产生其他异常时,事务不回滚,没有默认值,表示任何异常都回滚
                no-rollback-for:用于指定一个异常,当产生异常时,事务不回滚,产生其它异常时事务回滚,没有默认值,表示任何异常都回滚
        -->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!-- 配置aop -->
    <aop:config>
        <!-- 配置切入点表达式 -->
        <aop:pointcut id="tl" expression="execution(* com.wzk.service.impl.*.*(..))"/>
        <!-- 建立切入点表达式和事务通知的对应关系 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="tl"></aop:advisor>
    </aop:config>
</beans>

测试类

package com.wzk.test;

import com.wzk.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class JdbcTest {

    @Autowired
    private AccountService as;

    @Test
    public void test(){
        as.transfer("aaa","bbb",100f);
    }
}

半注解半xml

package com.wzk.dao;

import com.wzk.domain.Account;

public interface AccountDao  {

    Account findById(Integer accountId);

    Account findByName(String name);

    void updateAccount(Account account);
}


package com.wzk.dao.impl;

import com.wzk.dao.AccountDao;
import com.wzk.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate template;

    @Override
    public Account findById(Integer accountId) {
        List<Account> accounts = template.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        if(accounts.isEmpty()){
            return null;
        }else{
            return accounts.get(0);
        }
    }

    @Override
    public Account findByName(String name) {
        List<Account> accounts = template.query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),name);
        if(accounts.isEmpty()){
            return null;
        }else{
            return accounts.get(0);
        }
    }

    @Override
    public void updateAccount(Account account) {
        template.update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
}

package com.wzk.service;

import com.wzk.domain.Account;

public interface AccountService {

    Account findAccountById(Integer accountId);

    void transfer(String sourceName, String targerName, Float money);
}


package com.wzk.service.impl;

import com.wzk.dao.AccountDao;
import com.wzk.dao.impl.AccountDaoImpl;
import com.wzk.domain.Account;
import com.wzk.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//只读型事务
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDaoImpl accountDaoImpl;

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDaoImpl.findById(accountId);
    }

    //需要读写型事务
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer");
        Account source = accountDaoImpl.findByName(sourceName);
        Account target = accountDaoImpl.findByName(targetName);
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        accountDaoImpl.updateAccount(source);
        int i = 1/0;
        accountDaoImpl.updateAccount(target);
    }
}

<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.wzk"></context:component-scan>
    <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <!-- spring中基于注解的声明式事务控制配置步骤
            1、配置事务管理器
            2、开启spring对注解事务的支持
            3、在需要事务支持的地方使用@Transactional注解
     -->
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 开启spring对注解的支持 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

测试类

package com.wzk.test;

import com.wzk.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class JdbcTest {

    @Autowired
    private AccountService as;

    @Test
    public void test(){
        as.transfer("aaa","bbb",100f);
    }
}

全注解

dao和service

package com.wzk.dao;

import com.wzk.domain.Account;

public interface AccountDao  {

    Account findById(Integer accountId);

    Account findByName(String name);

    void updateAccount(Account account);
}




package com.wzk.dao.impl;

import com.wzk.dao.AccountDao;
import com.wzk.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate template;

    @Override
    public Account findById(Integer accountId) {
        List<Account> accounts = template.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        if(accounts.isEmpty()){
            return null;
        }else{
            return accounts.get(0);
        }
    }

    @Override
    public Account findByName(String name) {
        List<Account> accounts = template.query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),name);
        if(accounts.isEmpty()){
            return null;
        }else{
            return accounts.get(0);
        }
    }

    @Override
    public void updateAccount(Account account) {
        template.update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
}





package com.wzk.service;

import com.wzk.domain.Account;

public interface AccountService {

    Account findAccountById(Integer accountId);

    void transfer(String sourceName, String targerName, Float money);
}




package com.wzk.service.impl;

import com.wzk.dao.AccountDao;
import com.wzk.dao.impl.AccountDaoImpl;
import com.wzk.domain.Account;
import com.wzk.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//只读型事务
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDaoImpl accountDaoImpl;

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDaoImpl.findById(accountId);
    }

    //需要读写型事务
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer");
        Account source = accountDaoImpl.findByName(sourceName);
        Account target = accountDaoImpl.findByName(targetName);
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        accountDaoImpl.updateAccount(source);
        //int i = 1/0;
        accountDaoImpl.updateAccount(target);
    }
}

config的配置

package config;

import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * spring的配置类,相当于bean.xml
 */
@Configuration
@ComponentScan("com.wzk")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement
public class SpringConfiguration {
}

package config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * 和数据库相关的配置类
 */
public class JdbcConfig {

    @Value("${driver}")
    private String driver;

    @Value("${url}")
    private String url;

    @Value("${user}")
    private String username;

    @Value("${password}")
    private String password;

    /**
     * 创建JdbcTemplate对象
     * @param dataSource
     * @return
     */
    @Bean(name="jdbcTemplate")
    public JdbcTemplate createJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * 和事务相关的配置
 */
public class TransactionConfig {

    /**
     * 用于创建事务管理器对象
     * @param dataSource
     * @return
     */
    @Bean(name="transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}

jdbc.properties文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/spring
user=root
password=root
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值