spring入门3-jdbcTemplate简单使用和声明式事务

1.JdbcTemplate简单使用

1.1.引入相关依赖包

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.32</version>
</dependency>
<dependency>
  <groupId>c3p0</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.1.2</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.10</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.0.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.0.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>5.0.5.RELEASE</version>
</dependency>

1.2.创建spring配置

@Configuration
@ComponentScan({"ox"})
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {

    // 1.数据连接信息
    // jdbc.properties不能使用username这个key.spring占用了,所以要加前缀
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 2.创建数据源
     */
    @Bean
    public ComboPooledDataSource comboPooledDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 3.创建jdbcTemplate
     *       方法形参 自动注入
     */
    @Bean  
    public JdbcTemplate jdbcTemplate(ComboPooledDataSource comboPooledDataSource){
        return new JdbcTemplate(comboPooledDataSource);
    }
}

1.3.jdbcTemplate使用

a.聚合查询

@Test
public void t01(){
    Long count = jdbcTemplate.queryForObject(
        "select count(*) from account",
        Long.class);
    System.out.println("数据库有"+count+"条数据!");
}

b.查询单个数据

@Test
public void t02(){
    Account account = jdbcTemplate.queryForObject(
            "select * from account where name=?",
            new BeanPropertyRowMapper<Account>(Account.class),
            "张三");
    System.out.println(account);
}

c.查询多个

@Test
public void t03(){
    List<Account> accountList = jdbcTemplate.query(
        "select * from account",
        new BeanPropertyRowMapper<Account>(Account.class));

    for (Account account : accountList) {
        System.out.println(account);
    }
}

d.插入

@Test
public void t04(){
    Account account = new Account();
    account.setName("王五");
    account.setMoney(19.1d);
    int update = jdbcTemplate.update(
        "insert into account values(?,?)", 
        account.getName(), 
        account.getMoney());
    
    System.out.println(update > 0 ? "success" : "fail");
}

e.修改

@Test
public void t05(){
    int update = jdbcTemplate.update(
        "update account set money = 100 where name = ?",
        "王五");
    
    System.out.println(update > 0 ? "success" : "fail");
}

f.删除

@Test
public void t06(){
    int flag = jdbcTemplate.update(
        "delete from account where name =?",
        "王五");
    
    System.out.println(flag > 0 ? "success" : "fail");
}   

2.声明式事务

2.1.简述

2.2.相关对象

2.2.1.PlatformTransactionManager

PlatformTransactionManager 接口是 spring 的事务管理器,它里面提供了我们常用的操作事务的方法。
一般使用实现类DataSourceTransactionManager或HibernateTransactionManager

2.2.2.TransactionDefinition

TransactionDefinition 是事务的定义信息对象.定义了事务的隔离级别和传播行为

2.2.3.TransactionStatus

TransactionStatus 接口提供的是事务具体的运行状态

2.3 事务隔离级别

设置隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读和虚读。

  • ISOLATION_DEFAULT
  • ISOLATION_READ_UNCOMMITTED
  • ISOLATION_READ_COMMITTED
  • ISOLATION_REPEATABLE_READ
  • ISOLATION_SERIALIZABLE

2.4 事务传播行为

  • REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
  • SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
  • MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
  • REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
  • NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
  • NEVER:以非事务方式运行,如果当前存在事务,抛出异常
  • NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作
  • 超时时间:默认值是-1,没有超时限制。如果有,以秒为单位进行设置
  • 是否只读:建议查询时设置为只读

2.5.基于xml的声明式事务

2.5.1.什么时声明式事务

是什么:在配置文件中声明,用在 Spring 配置文件中声明式的处理事务来代替代码式的处理事务。
作用:事务管理不侵入开发的组件
底层:Spring 声明式事务控制底层就是AOP

2.5.2.配置实现

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

      <!--平台事务管理器-->
      <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource"></property>
      </bean>

      <!--事务增强配置-->
      <tx:advice id="txAdvice" transaction-manager="transactionManager">
          <tx:attributes>
              <tx:method name="*"/>
          </tx:attributes>
      </tx:advice> 

      <!--事务的aop增强-->
      <aop:config>
          <aop:pointcut id="myPointcut" expression="execution(* xxx.yyy.service.impl.*.*(..))"/>
          <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"></aop:advisor>
      </aop:config>

2.5.3.切点方法的事务参数的配置

<!--事务增强配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>

其中,tx:method 代表切点方法的事务参数的配置,例如:

<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>
  • name:切点方法名称
  • isolation:事务的隔离级别
  • propogation:事务的传播行为
  • timeout:超时时间
  • read-only:是否只读

2.6.基于注解的声明式事务

2.6.1.使用步骤

a.在需要事务控制的类或方法上添加@Transactional
b.在xml中开启事务的注解驱动

<tx:annotation-driven/>

2.6.2.@Transactional

  • 使用 @Transactional 在需要进行事务控制的类或是方法上修饰,注解可用的属性同 xml 配置方式,例如隔离级别、传播行为等。
  • 注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置。
  • 使用在方法上,不同的方法可以采用不同的事务参数配置。
  • Xml配置文件中要开启事务的注解驱动<tx:annotation-driven/>
  • 注解配置文件中开启事务注解驱动@EnableTransactionManagement
posted @ 2020-07-18 01:46  xia-qaq  阅读(189)  评论(0编辑  收藏  举报