Spring笔记(3)

一、JDBC Template基本使用

1.开发步骤

1.1直接使用template

  1. 导入spring-jdbc和spring-tx坐标

    <!--    JDBC-->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.0.3.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>5.0.3.RELEASE</version>
        </dependency>
        <!--  druid-->
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.0.9</version>
        </dependency>
        <!--      c3po-->
        <dependency>
          <groupId>c3p0</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.1.2</version>
        </dependency>
    <!--    mysql -->
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.23</version>
        </dependency>
      </dependencies>
    
  2. 创建数据库表和实体

  3. 创建JDBCTemplate对象

  4. 执行数据库操作

    /**
     * 测试JDBCTemplate开发步骤
     */
    @Test
    public void jdbcTest() throws PropertyVetoException {
        //创建数据源 c3p0
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/account");
        dataSource.setUser("root");
        dataSource.setPassword("gyb20010204");
    
        //创建template
        JdbcTemplate template = new JdbcTemplate();
        //设置数据源
        template.setDataSource(dataSource);
        //执行操作
        int rows = template.update("insert into account values(?,?)", "tom", 200);
        System.out.println(rows);
    }
    

1.2使用Spring容器注入template

  1. 注入bean对象

  2. 依赖注入数据源

    <!--    注入数据源对象-->
        <bean id ="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/account"/>
            <property name="user" value="root"/>
            <property name="password" value="gyb20010204"/>
        </bean>
    <!--    注入jdbc模板对象-->
        <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--        依赖注入数据源-->
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
  3. 测试

    @Test
    public void jdbcSpringTest(){
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate template = app.getBean(JdbcTemplate.class);
        int rows = template.update("insert into account values(?,?)", "jack", 300);
        System.out.println(rows);
    }
    

2.CRUD操作

增,删,改:update

int rows = template.update("insert into account values(?,?)", "jack", 300);

查:query(结果为list集合)

	List<Account> accountList = template.query(sql, new BeanPropertyRowMapper<Account>(Account.class));

queryForObject(结果为 对象)

	Account account = template.queryForObject(sql, new BeanPropertyRowMapper<Account>(Account.class));

queryForObject(结果为数字)

	Integer integer = template.queryForObject("select count(*) from account", Integer.class);

二、Spring的事务控制

1.编程事务控制相关对象

管理+定义 = 状态

1.1 PlatformTransactionManager 事务平台管理器 接口(需要配置)

实现根据不同的dao层技术来实现

​ ①、TransactionStatus getTransaction(TransactionDefinition definition) ,事务管理器 通过TransactionDefinition,获得“事务状 态”,从而管理事务。

​ ②、void commit(TransactionStatus status) 根据状态提交

​ ③、void rollback(TransactionStatus status) 根据状态回滚

1.2.TransactionDefinition 事务定义 接口(需要配合)

  • ​ 设置事务隔离级别
  • ​ 设置事务传播行为

​ Spring中的7个事务传播行为:

---- 如果A调用B 假设A.., 则....
PROPAGATION_REQUIRED 支持当前事务,假设当前没有事务。就新建一个事务
PROPAGATION_SUPPORTS 支持当前事务,假设当前没有事务,就以非事务方式运行
PROPAGATION_MANDATORY 支持当前事务,假设当前没有事务,就抛出异常
PROPAGATION_REQUIRES_NEW 新建事务,假设当前存在事务。把当前事务挂起
PROPAGATION_NOT_SUPPORTED 以非事务方式运行操作。假设当前存在事务,就把当前事务挂起
PROPAGATION_NEVER 以非事务方式运行,假设当前存在事务,则抛出异常
PROPAGATION_NESTED 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作。
超时时间
是否只读

1.3.TransactionStatus 事务状态(被动 不需要配置)

名称 说明
void flush() 刷新事务
boolean hasSavepoint() 获取是否存在保存点
boolean isCompleted() 获取事务是否完成
boolean isNewTransaction() 获取是否是新事务
boolean isRollbackOnly() 获取是否回滚
void setRollbackOnly() 设置事务回滚

2.基于XML的声明式事务控制

2.1作用

业务代码事务控制通过 事务配置 的方式进行松耦合

2.3方法

​ 采用AOP的思想:切点(业务)

通知(事务控制)

​ 将业务进行增强,从而达成事务配置,并且松耦合

2.4步骤

  1. 创建目标对象,编写切入点

  2. 在applicationContext中配置[平台事务管理器](#1.1 PlatformTransactionManager 事务平台管理器 接口(需要配置)),其中配置数据源(上一章中的平台事务管理器)

    <!--    平台事务管理器-->
        <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
  3. 在applicationContext中加入tx命名空间

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           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">
    
  4. 编写事务的增强,将平台事务管理器配入(上一章中的[事务定义](#1.2.TransactionDefinition 事务定义 接口(需要配合)))

    <!--    通知,事务的增强-->
        <tx:advice id="txAdvice" transaction-manager="transactionManger">
    <!--        配置事物的属性信息-->
            <tx:attributes>
                <tx:method name="trans" isolation="DEFAULT"/>
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
    
  5. 编写AOP配置(配入切点(事务)配入增强(事务增强))

    <!--    配置织入-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* Service.Impl.*.*(..))"></aop:advisor>
    </aop:config>

3.基于注解的声明式事务控制

注意:

  1. 使用@Transactional在需要进行事务控制的或者方法上修饰,注解也可配入事务定义信息
  2. 注解使用在类上,那么该类下的所有方法都是用同一套注解参数配置
  3. xml配置文件中要开启事务注解驱动注解扫描
<tx:annotation-driven/>
posted @ 2021-08-26 17:34  橡皮筋儿  阅读(24)  评论(0编辑  收藏  举报