Spring笔记(3)

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/>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/115199.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Matlab 2016a 安装包及破解教程

    Matlab 2016a 安装包及破解教程Matlab-Matlab2016a安装破解教程本方法只是研究破解技术所用。如果要使用软件还是要用正版的。Matlab2016a安装包及破解教程百度云分享链接: 链接:https://pan.baidu.com/s/1i6BgD8p    密码:17gg Matlab安装教程: 1、下载文件,得到R2016a_win64.part1.rar、R2016a_…

    2022年5月1日
    268
  • c++的条件运算符_条件运算符都有哪些

    c++的条件运算符_条件运算符都有哪些一、运算符1.条件运算符(?:)是C语言中唯一的一个三目运算符,它是对第一个表达式作真/假检测,然后根据结果返回另外两个表达式中的一个。&amp;amp;amp;amp;amp;amp;amp;lt;表达式1&amp;amp;amp;amp;amp;amp;amp;gt;?&amp;amp;amp;amp;amp;amp;amp;lt;表达式2&amp;amp;amp;amp;amp;amp;amp;gt;:&amp;amp;amp;amp;amp;amp;a

    2022年9月27日
    5
  • 英语考研词汇[通俗易懂]

    英语考研词汇[通俗易懂]1.WithmyownearsIclearlyheardtheheartbeatofthenuclearbomb.我亲耳清楚地听到原子弹的心脏的跳动。2.Nextyearthebeardedbearwillbearadearbabyintherear.明年,长胡子的熊将在后方产一头可爱的小崽.3.EarlyIsearchedt

    2022年5月12日
    41
  • 观察者模式observer不适用于_观察者模式代码

    观察者模式observer不适用于_观察者模式代码观察者模式Obeserver动机模式定义实例结构图要点总结笔记动机在软件构建过程中,我们需要为某些对象建立 一种“通知依赖关系” —-一个对象发(目标对象)的状态发生改变,所有依赖的对象(观察者对象)都将很好的得到通知。如果这样的依赖关系过于紧密。将使软件不能很好的抵御变化使用面向对象技术 可以将这种依赖关系弱化,并形成一种稳定的依赖关系。从而实现软件体系结构的松耦合。模式定义定义对象间的一种一对多(变化)的依赖关系,以便当一个对象(subject)的状态发生改变时,所有依赖于它的对象都得到通

    2022年8月9日
    5
  • python tkinter窗口美化_jquery进度条插件

    python tkinter窗口美化_jquery进度条插件前言在我们进行自动化测试的时候,用例往往是成百上千,执行的时间是几十分钟或者是小时级别。有时,我们在调试那么多用例的时候,不知道执行到什么程度了,而pytest-sugar插件能很好解决我们的痛点。

    2022年7月29日
    9
  • QListWidget 布局方向设定

    QListWidget 布局方向设定//我们看下官方文档的说明//创建一个QListWidgetQListWidget m_list //假如m_list添加了很多子项(一个子项由一个图片和一段文字组成) //如果设置为m_second_list->setViewMode(QListView::IconMode); //那么m_list子项就会从左到右横向的排列

    2022年6月5日
    139

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号