spring事务:事务控制方式,使用AOP控制事务,七种事务传播行为,声明事务,模板对象,模板对象原理分析
发布日期:2021-05-08 23:13:33 浏览次数:20 分类:博客文章

本文共 30055 字,大约阅读时间需要 100 分钟。

���������������

������������

1)������������

1.1)���������������-������01

 

 

���������������������������������������������������������������������������������������������������������������������������������

1.2)���������������

���������������ACID���

  • ������������Atomicity������������������������������������������������������������������������������������������

  • ������������Consistency���������������������������������������������������������������������������������100���������������������������������������������������������������������������������������������100������������������������������100������������������������������������������������������������

  • ������������Isolation���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

  • ������������Durability���������������������������������������������������������������������������������������������������������������������������������������������������������������������������

1.3)���������������������

���������������isolation level

���������������������������������������������������������������������������������������������������������������������������������������������������

  • ���������������������������������������Read uncommitted������������������Read committed������������������ 

 

 

  • ���������������������B������������500���������������������������������A���������������������������100���������������A���������������B���������������������������������������������������������������500���

    xxxxxxxxxx ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
  • ������������������A���������������B���������������������������������

    ��������������� Repeatable read ������������������MySQL InnoDB������������

    A������������������������������B������������������100������A���������������������������������������������

     

     

    ���������������������T4������������T7������������������������������������������

  • ���������������������������������������������������

    ���������������������������������������������������������������������������������������������������������������������������������������������������������100������������������������������������������������������

     

     

    ��������������� Serializable������������������

������������������������������������������������������������������������������������������������������������������������������������

  • ������������(Read Uncommitted)������������������������������������������������������������������������������������������������

  • ���������(Read Committed)������������������������������������������������������������������

  • ������������(Repeatable Read)������������������MySQL InnoDB������������������SQL���������������������������������������������������������������������������

  • ���������(Serializable)���������������������������������Serializable���������������������������������������������������������������������������������������������������������������������������Serializable���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Serializable���������������

2)������������

���������������������������������

 

 

2.1)Spring������������������-������02

Spring������������������������������������������������������������������������

  • ���������������������TransactionDefinition

  • ���������������TransactionStatus

  • ������������������������PlatformTransactionManager

2.2)TransactionDefinition

���������������������������������������

  • ������������������������

    String getName()
  • ���������������������������

    boolean isReadOnly()
  • ������������������������

    int getIsolationLevel()
  • ���������������������

    int getTimeout()
  • ������������������������������

    int getPropagationBehavior()

2.3)TransactionStatus

���������������������������������������������������������������������������������������������������

 

 

2.4)PlatformTransactionManager

  • ������������������������������

    • DataSourceTransactionManager ���������Spring JDBC���MyBatis

    • HibernateTransactionManager ���������Hibernate3.0���������������

    • JpaTransactionManager ���������JPA

    • JdoTransactionManager ���������JDO

    • JtaTransactionManager ���������JTA

  • JPA���Java Persistence API���Java EE ������������������POJO������������������������������������������������������������������API���������JPA���������������������������������JPA���������������

  • JDO(Java Data Object )���Java������������������������������������������������������������������������������������API������JDBC���������JDBC���������������������������������������JDO������������������������������������������XML���������������������ODBMS���������������������������

  • JTA���Java Transaction API���Java EE ������������������������������������������������������������������JDBC���������JDBC���������������������������������������������������������������JTA���������������������������������������JDBC���������JDO ������������������������JTA���������

���������������������������������������

  • ������������ ���

    TransactionStatus getTransaction(TransactionDefinition definition)

     

  • ������������ ���

    void commit(TransactionStatus status)

     

  • ������������ ���

    void rollback(TransactionStatus status)

     

2.5)������������������-������03

  • ���������

  • ������������������������XML���

  • ���������������������������������

2.6)������������

2.6.1)������������

���������������������������������A���������B���������������������������������������������������������������������������

2.6.2)������������������

  • ���������AccountDao������������������������������������

    /** * ������������ * @param name      ��������������� * @param money     ������������ */void inMoney(@Param("name") String name, @Param("money") Double money);/** * ������������ * @param name      ��������������� * @param money     ������������ */void outMoney(@Param("name") String name, @Param("money") Double money);

     

    AccountDao.xml

    update account set money = money + #{money} where name = #{name}
    update account set money = money - #{money} where name = #{name}

     

  • ���������������AccountService������������������

    /*** ������������* @param outName     ���������������* @param inName      ���������������* @param money       ������������*/public void transfer(String outName,String inName,Double money);

     

  • ������������������������������������AccountServiceImpl

    public void transfer(String outName,String inName,Double money){        accountDao.outMoney(outName,money);        accountDao.inMoney(inName,money);}

     

2.6.3)���������������-������04

  1. ���AccountServiceImpl������������������������

    private DataSource dataSource;public void setDataSource(DataSource dataSource) {    this.dataSource = dataSource;}public void transfer(String outName, String inName, Double money) {    //1.���������������������,������������������������������������������������������    PlatformTransactionManager ptm = new DataSourceTransactionManager(dataSource);    //2.������������    TransactionDefinition td = new DefaultTransactionDefinition();    //3.������������������������������������������������������������������    TransactionStatus ts = ptm.getTransaction(td);        accountDao.outMoney(outName,money);    //������������������������������������������    int i = 1/0;    accountDao.inMoney(inName,money);        //4.������������    ptm.commit(ts);}

     

  2. ���applicationContext.xml���������Spring���MyBatis���������

     

  3. ���accountService���������accountDao���dataSource������������

     

  4. ������������

    public class App {    public static void main(String[] args) {        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");        AccountService accountService = (AccountService) ctx.getBean("accountService");        accountService.transfer("tom","itheima",100D);    }}

     

 

2.7)������AOP������������-������05

1.������������������������������������������������������AOP������������������������������������������������

public Object tx(ProceedingJoinPoint pjp) throws Throwable {    DataSourceTransactionManager dstm = new DataSourceTransactionManager();    dstm.setDataSource(dataSource);    TransactionDefinition td = new DefaultTransactionDefinition();    TransactionStatus ts = dstm.getTransaction(td);        Object ret = pjp.proceed(pjp.getArgs());        dstm.commit(ts);    return ret;}

 

2.���applicationContext.xml���������AOP���������������������dataSource

 

3.������������������AOP���������������������������������������������������������������������������

 

4.������������

public class App {    public static void main(String[] args) {        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");        AccountService accountService = (AccountService) ctx.getBean("accountService");        accountService.transfer("tom","itheima",100D);    }}

 

 

2.8������������������XML���

���������������������������������tx���������������

 

2.8.1)tx:advice

  • ���������tx:advice

  • ���������������

  • ���������beans������

  • ������������������������������������

  • ���������

     

  • ���������������

    • id ���������������aop���������������������id

    • transaction-manager ������������������������bean

2.8.2)tx:attributes

  • ���������tx:attributes

  • ���������������

  • ���������tx:advice������

  • ���������������������������

  • ���������

     

2.8.3)aop:advisor

������aop:advisor���AOP������������������������������������

 

 

2.8.4) ������XML������������

  1. ���������������������

     

  2. ���������������������������

     

  3. AOP���������������������������������������������

     

  4. ������������

    public class App {    public static void main(String[] args) {        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");        AccountService accountService = (AccountService) ctx.getBean("accountService");        accountService.transfer("tom","itheima",100D);    }}

     

     

������������������������

J2EE���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

2.8.5)tx:method-������07

  • ���������tx:method

  • ���������������

  • ���������tx:attribute������

  • ������������������������������������

  • ���������

     

  • ���������

    ������������������������������������������1������������������������������1���������������������������������

tx:method������

 

 

2.9)������������������-������08

 

 

  • ������������������������������������������������������������������������������������������������������������������������������

    public void methond1() {    //������������������    methond2();        //doSomething}public void methond2() {    //������������������    //doSomething}

     

2.10)������������������������(������)

Spring������������������������������������������������ REQUIRED

  • REQUIRED(������): ��������������������������������������������������������������������������������������������������������� 

������

 

 

  • REQUIRES_NEW(������������): ��������������������������������������������������������������� 

������

 

 

  • SUPPORTS: ��������������������������������������������������������������������������� 

 

  • NOT_SUPPORTED: ������������������������������������������������������������������������������������ 

 

  • MANDATORY(���������): ������������������������������������������������������������������ 

 

  • NEVER: ��������������������������������������������������������������������� 

  • NESTED: ��������������������������������������������������������������������������������������������� REQUIRED������������������

2.11)������������������������

������������������������3���������������������

  1. ���������S1������������������������������log

  2. ���������S2������������������������������������order

  3. ���������S3������������������Z������������������������order_pay

 

 

������S2���S3���������������������S1������������������������������������������������������������������S1���������������������������������

���������������S1���������������������������������������������������������REQUIRES_NEW

2.12)���������������������������-������09

2.12.1)@Transactional

  • ���������@Transactional

  • ������������������������������������������������

  • ������������������������������������������������������������������

  • ������������������������/������������������������������������������������������������������������������

  • ���������

    @Transactional(    readOnly = false,    timeout = -1,    isolation = Isolation.DEFAULT,    rollbackFor = {ArithmeticException.class, IOException.class},    noRollbackFor = {},    propagation = Propagation.REQUIRES_NEW)public void methond() {}

     

  • ������������

    • ��������������� public ��������������������� protected���private������������������������������������������������������������������������������������������������

    • ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

2.12.2)tx:annotation-driven

  • ���������tx:annotation-driven

  • ���������������

  • ���������beans������

  • ���������������������������������������������������������������������

  • ���������

     

2.12.3 ������������������������������������

1.���applicationContext.xml���������������������

 

2.���transfer���������������@Transactional������������������������

@Transactional(        readOnly = false,        timeout = -1,        isolation = Isolation.DEFAULT,        rollbackFor = {},        noRollbackFor = {},        propagation = Propagation.REQUIRED)public void transfer(String outName, String inName, Double money) {    accountDao.outMoney(outName,money);    int i = 1/0;    accountDao.inMoney(inName,money);}

 

3.������������

public class App {    public static void main(String[] args) {        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");        AccountService accountService = (AccountService) ctx.getBean("accountService");        accountService.transfer("tom","itheima",100D);    }}

 

 

2.13)���������������(���������������)-������10

  • ���������@EnableTransactionManagement

  • ������������������

  • ���������Spring���������������������

  • ������������������������������������XML������������������������

  • ���������

    public class TransactionManagerConfig {    @Bean    public PlatformTransactionManager getTransactionManager(@Autowired DataSource dataSource){        return new DataSourceTransactionManager(dataSource);    }}

     

������������������������SpringConfig������������TransactionManagerConfig

@Import({JDBCConfig.class,MyBatisConfig.class,TransactionManagerConfig.class})  @EnableTransactionManagement  @Configuration  @ComponentScan("com.itheima")  @PropertySource("classpath:jdbc.properties")  @Import({JDBCConfig.class,MyBatisConfig.class,TransactionManagerConfig.class})  @EnableTransactionManagement  public class SpringConfig {  }

 

 

3)������������������������

3.1)Spring������������-������11

Spring������������������������������

  • JdbcTemplate

  • RedisTemplate

  • RestTemplate

  • RabbitTemplate

  • TransactionTemplate

  • JmsTemplate

  • HibernateTemplate

  • ...

3.2)JdbcTemplate

3.2.1 JdbcTemplate������

JdbcTemplate���Spring���JDBC���������������������������sql������������API���������������JDBC���������������������

  1. update���������������INSERT���UPDATE���DELETE������������

    public void save(Account account) {    String sql = "insert into account(name,money)values(?,?)";    jdbcTemplate.update(sql,account.getName(),account.getMoney());}

     

  2. queryXxx���������������SELECT���������������������

    public String findNameById(Integer id) {    String sql = "select name from account where id = ? ";    //������������������������������������������������������������������������������������������������name���String������    return jdbcTemplate.queryForObject(sql,String.class,id );}

     

3.2.1 ������JdbcTemplate

  1. ���JDBCConfig������������JdbcTemplate

    public class JDBCConfig {    @Value("${jdbc.driver}")    private String driver;    @Value("${jdbc.url}")    private String url;    @Value("${jdbc.username}")    private String userName;    @Value("${jdbc.password}")    private String password;    @Bean("dataSource")    public DataSource getDataSource(){        DruidDataSource ds = new DruidDataSource();        ds.setDriverClassName(driver);        ds.setUrl(url);        ds.setUsername(userName);        ds.setPassword(password);        return ds;    }    //������JdbcTemplate������������bean    @Bean("jdbcTemplate")    public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource){        return new JdbcTemplate(dataSource);    }    @Bean("jdbcTemplate2")    public NamedParameterJdbcTemplate getJdbcTemplate2(@Autowired DataSource dataSource){        return new NamedParameterJdbcTemplate(dataSource);    }}

     

  2. ������JdbcTemplate������AccountDaoImpl������������������

    //dao���������bean@Repository("accountDao")public class AccountDaoImpl implements AccountDao {    //������������������    @Autowired    private JdbcTemplate jdbcTemplate;    public void save(Account account) {        String sql = "insert into account(name,money)values(?,?)";        jdbcTemplate.update(sql, account.getName(), account.getMoney());    }    public void delete(Integer id) {        String sql = "delete from account where id = ?";        jdbcTemplate.update(sql, id);    }    public void update(Account account) {        String sql = "update account set name = ? , money = ? where id = ?";        jdbcTemplate.update(sql, account.getName(), account.getMoney(), account.getId());    }    public String findNameById(Integer id) {        String sql = "select name from account where id = ? ";        //������������������������������������������������������������������������������������������������name���String������        return jdbcTemplate.queryForObject(sql, String.class, id);    }    public Account findById(Integer id) {        String sql = "select * from account where id = ? ";        //���������������������������������        //RowMapper
    rm = new RowMapper
    () { // public Account mapRow(ResultSet rs, int rowNum) throws SQLException { // Account account = new Account(); // account.setId(rs.getInt("id")); // account.setName(rs.getString("name")); // account.setMoney(rs.getDouble("money")); // return account; // } //}; //return jdbcTemplate.queryForObject(sql, rm, id); return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper
    (Account.class), id); } public List
    findAll() { String sql = "select * from account"; //������spring��������������������������������������������������������� return jdbcTemplate.query(sql, new BeanPropertyRowMapper
    (Account.class)); } public List
    findAll(int pageNum, int pageSize) { String sql = "select * from account limit ?,?"; //������������������������������������ return jdbcTemplate.query(sql, new BeanPropertyRowMapper
    (Account.class), (pageNum - 1) * pageSize, pageSize); } public Long getCount() { String sql = "select count(id) from account "; //���������������������������������������������������������������������������������������������������������������Long������ return jdbcTemplate.queryForObject(sql, Long.class); }}

     

  3. ������AccountService������������������

    //������spring���������������������@RunWith(SpringJUnit4ClassRunner.class)//���������������spring������������������������@ContextConfiguration(classes = SpringConfig.class)public class AccountServiceTest {    @Autowired    private AccountService accountService;    @Test    public void testSave() {        Account account = new Account();        account.setName("������������");        account.setMoney(999.99d);        accountService.save(account);    }    @Test    public void testDelete() {        accountService.delete(21);    }    @Test    public void testUpdate() {        Account account = new Account();        account.setId(13);        account.setName("itheima");        account.setMoney(6666666666.66d);        accountService.update(account);    }    @Test    public void testFindNameById() {        String name = accountService.findNameById(13);        System.out.println(name);    }    @Test    public void testFindById() {        Account account = accountService.findById(13);        System.out.println(account);    }    @Test    public void testFindAll() {        List
    list = accountService.findAll(); System.out.println(list); } @Test public void testFindAll1() { List
    list = accountService.findAll(2, 2); System.out.println(list); } @Test public void testGetCount() { Long count = accountService.getCount(); System.out.println(count); }}

     

3.3)NamedParameterJdbcTemplate

���������������������sql������������API

  1. ������������AccountDao������������AccountDaoImpl2

    //dao���������bean@Repository("accountDao2")@Primarypublic class AccountDaoImpl2 implements AccountDao {    //������������������    @Autowired    private NamedParameterJdbcTemplate jdbcTemplate;    public void save(Account account) {        System.out.println(this.getClass().getName());        String sql = "insert into account(name,money)values(:name,:money)";        Map pm = new HashMap();        pm.put("name",account.getName());        pm.put("money",account.getMoney());        System.out.println("NamedParameterJdbcTemplate");        jdbcTemplate.update(sql,pm);    }    public void delete(Integer id) {    }    public void update(Account account) {    }    public String findNameById(Integer id) {        return null;    }    public Account findById(Integer id) {        return null;    }    public List
    findAll() { return null; } public List
    findAll(int pageNum, int preNum) { return null; } public Long getCount() { return null; }}

     

  2. ������NamedParameterJdbcTemplate������

    //������spring���������������������@RunWith(SpringJUnit4ClassRunner.class)//���������������spring������������������������@ContextConfiguration(classes = SpringConfig.class)public class AccountServiceTest {    @Autowired    private AccountService accountService;    @Test    public void testSave() {        Account account = new Account();        account.setName("������������");        account.setMoney(999.99d);        accountService.save(account);    }}

     

     

     

     

3.4)RedisTemplate(������)

3.4.1)������������-������12

  1. ������redis.conf

    bind 0.0.0.0port 6379protected-mode no

     

  2. ������Redis

    • Linux

      redis-server redis.conf

       

    • Windows���������Redis���������������������redis-server.exe

  3. ������Redis���������

    #������Redis���������: Linux
    redis-cli

     

    #������Redis���������: Windows#������redis-cli.exe

     

3.4.2)������������-������13

RedisTemplate���������������������������������4������

  • ��������������������� 

 

 

  • ���������Operations������������������������ 

 

 

 

 
public void changeMoney(Integer id, Double money) {    redisTemplate.opsForValue().set("account:id:"+id,money);}public Double findMondyById(Integer id) {    Object money = redisTemplate.opsForValue().get("account:id:" + id);    return new Double(money.toString());}

 

  • Bound Operations��������������������������� 

 

 

������������ 

 

 

3.4.3 ������RedisTemplate

  1. ���resources���������������redis.properties

    # redis���������������������redis.host=127.0.0.1#redis���������������������redis.port=6379

     

    #redis���������������������#redis.password=itheima#������������������redis.maxActive=20#������������������redis.maxIdle=10#������������������redis.minIdle=0#������������������redis.maxWait=-1

     

  2. ������RedisConfig������������com.itheima.config

    package com.itheima.config;@PropertySource("redis.properties")public class RedisConfig {    @Value("${redis.host}")    private String hostName;    @Value("${redis.port}")    private Integer port;//    @Value("${redis.password}")//    private String password;    @Value("${redis.maxActive}")    private Integer maxActive;    @Value("${redis.minIdle}")    private Integer minIdle;    @Value("${redis.maxIdle}")    private Integer maxIdle;    @Value("${redis.maxWait}")    private Integer maxWait;

     

    @Bean    //������RedisTemplate    public RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory){        //1.������������        RedisTemplate redisTemplate = new RedisTemplate();        //2.������������������        redisTemplate.setConnectionFactory(redisConnectionFactory);        //3.������redis���������key���������������������key������������������        RedisSerializer stringSerializer = new StringRedisSerializer();        redisTemplate.setKeySerializer(stringSerializer);        redisTemplate.setHashKeySerializer(stringSerializer);        //4.������        return redisTemplate;    }
    @Bean    //������Redis������������    public RedisConnectionFactory createRedisConnectionFactory(RedisStandaloneConfiguration redisStandaloneConfiguration,GenericObjectPoolConfig genericObjectPoolConfig){        //1.������������������������������������������������������Jedis���������        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder builder = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder)JedisClientConfiguration.builder();        //2.������������������������������        builder.poolConfig(genericObjectPoolConfig);        //3.������Jedis������������        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration,builder.build());        //4.������        return jedisConnectionFactory;    }    @Bean    //������spring���������Redis���������������    public GenericObjectPoolConfig createGenericObjectPoolConfig(){        //1.������Jedis������������������������        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();        //2.���������������������        genericObjectPoolConfig.setMaxTotal(maxActive);        genericObjectPoolConfig.setMinIdle(minIdle);        genericObjectPoolConfig.setMaxIdle(maxIdle);        genericObjectPoolConfig.setMaxWaitMillis(maxWait);        //3.������        return genericObjectPoolConfig;    }

     

    @Bean    //������Redis������������������������    public RedisStandaloneConfiguration createRedisStandaloneConfiguration(){        //1.������Redis���������������������������        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();        //2.������Redis������������������������������������������������������������        redisStandaloneConfiguration.setHostName(hostName);        redisStandaloneConfiguration.setPort(port);//        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));        //3.������        return redisStandaloneConfiguration;    }}

     

  3. AccountService

    public interface AccountService {    void changeMoney(Integer id,Double money);    Double findMoneyById(Integer id);}

     

  4. AccountServiceImpl���������redis������changeMoney���findMoneyById

    @Service("accountService")public class AccountServiceImpl implements AccountService {    @Autowired    private RedisTemplate redisTemplate;    public void changeMoney(Integer id, Double money) {        //���������redis���set account:id:1 100        redisTemplate.opsForValue().set("account:id:"+id, money);    }    public Double findMoneyById(Integer id) {        //���������redis���get account:id:1        Object money = redisTemplate.opsForValue().get("account:id:"+id);        return new Double(money.toString());    }}

     

  5. ���������������������AccountServiceTest

    //������spring���������������������@RunWith(SpringJUnit4ClassRunner.class)//���������������spring������������������������@ContextConfiguration(classes = SpringConfig.class)public class AccountServiceTest {    @Autowired    private AccountService accountService;    @Test    public void test(){        Jedis jedis = new Jedis("127.0.0.1",6379);        jedis.set("name","itheima");        System.out.println(jedis.get("name"));        jedis.close();    }    @Test    public void changeMoney() {        accountService.changeMoney(1,100D);    }    @Test    public void findMoneyById() {        Double money = accountService.findMoneyById(1);        System.out.println(money);    }}

     

4)������������������������

4.1)������������-������14

������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

������������(Strategy Pattern)���������������������������������������������������������������������������������������������

 

 

���������������������

 

 

4.2)������������������

���������������������������������������������������������������������������

  • JdbcTemplatepublic void save(Account account) {    String sql = "insert into account(name,money)values(?,?)";    jdbcTemplate.update(sql, account.getName(), account.getMoney());}

     

  • NamedParameterJdbcTemplatepublic void save(Account account) {    System.out.println(this.getClass().getName());    String sql = "insert into account(name,money)values(:name,:money)";    Map pm = new HashMap();    pm.put("name",account.getName());    pm.put("money",account.getMoney());    System.out.println("NamedParameterJdbcTemplate");    jdbcTemplate.update(sql,pm);}

     

上一篇:Web全段重点整理
下一篇:Maven基础&&Spring框架阶段常用工具类整理

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2025年04月30日 17时00分05秒