Spring(四)——Spring的JdbcTemplate和事务控制

1 Spring的JdbcTemplate

Spring框架对jdbc进行的薄薄的封装。

作用:

  • 用于和数据库交互的,实现对表的curd操作。

1.1 如何获取该对象

  • 添加依赖:
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>
    </dependencies>
  • 测试:

直接创建对象方法:

        //准备数据源:spring内置数据源,可以自己ioc
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/testspring");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("root");
        //创建JdbcTemplate对象
        JdbcTemplate jt = new JdbcTemplate(driverManagerDataSource);
        // 或者设置 jt.setDataSource(driverManagerDataSource);
        jt.execute("insert account(name,money) values('cdc',1000)");

使用ioc的方法:

配置bean.xml

<!--    配置jdbcTemplate-->
    <bean id="jdbcTemplate" 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/testspring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

执行

//获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
jt.execute("insert into account(name,money) values('eee',1000)");

1.2 JdbcTemplate的crud操作

  • 保存
jt.update("insert into account(name,money) values(?,?)","fff",2233);
  • 更新
jt.update("update account set name = ?,money = ? where id = ?","test",7777,7);
  • 删除
jt.update("delete from account where id = ?",8);
  • 查询所有
List<account> accountList = jt.query("select * from account where money > ? ", new RowMapper<account>() {
   /**
    * 把结果数据封装到account中,再由spring将每一个account加到集合中
    * @param resultSet
    * @param i
    * @return
    * @throws SQLException
    */
    public account mapRow(ResultSet resultSet, int i) throws SQLException {
        account a = new account();
        a.setId(resultSet.getInt("id"));
        a.setMoney(resultSet.getFloat("money"));
        a.setName(resultSet.getString("name"));
        return a;
    }
}, 2000f);
//或者
List<account> accountList = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<account>(account.class),1000f);
  • 查询一个
//有单独查询一个的方法,但这种方法更常用
List<account> accountList = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<account>(account.class),1);
System.out.println(accountList.isEmpty()?"没有内容":accountList.get(0));
  • 查询返回一行一列
int count = jt.queryForObject("select count(*) from account where money > ?",Integer.class,2000f);

1.3 JdbcDaoSupport

当定义多个dao实现类,每个类都要定义JdbcTemplate,增加了许多重复代码,可以继承一个JdbcDaoSupport类,作为dao实现类的父类,里面有JdbcTemplate,抽取重复代码。

注意:使用此方法要在dao的配置中注入dataSource
在这里插入图片描述

2 Spring的声明式事务控制

JavaEE体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方法。
spring框架为我们提供了一组事务控制的接口。
spring的事务控制都是基于aop的。既可以通过编程实现,也可以通过配置实现。

2.1 PlatformTransactionManager

此接口是spring的事务管理器,它里面提供了我们常用的操作事务的方法。

  • 获取事务状态信息:
    在这里插入图片描述

  • 提交事务:
    在这里插入图片描述

  • 回滚事务:
    在这里插入图片描述

常用的管理事务的对象:

  • org.springframework.jdbc.datasource.DataSourceTransactionManager
    使用SpringJDBC 或 iBatis 进行持久化数据时使用 进行持久化数据时使用
  • org.springframework.orm.hibernate5.HibernateTransactionManager
    使用Hibernate 版本进行持久化数据时使用 版本进行持久化数据时使用

2.2 TransactionDefinition

它是事务的定义信息对象。

  • 获取事务对象名称:
    String getName()
  • 获取事务隔离级别:
    int getIsolationLevel()
  • 获取事务传播行为:
    int getPropagationBehavior()
  • 获取事务超时时间(默认值是-1,没有超时限制。如果有,以秒为单位进行设置):
    int getTimeout()
  • 获取事务是否只读(只读:查询;读写:增删改):
    boolean isReadOnly()

事务隔离级反映事务提交并发访问时的处理态度

隔离级处理态度
ISOLATION_DEFAULT默认级别,归属下列某一种
ISOlATION_READ_UNCOMMITTED可以读取未提交数据
ISOLATION_READ_COMMITTED只能读取已提交数据,解决脏读问题(Oracle默认级别)
ISOLATION_REPEATABLE_READ是否读取其他事务提交修改后的数据,解决不可重复读问题(Mysql默认级别)
ISOLATION_SERIALIZABLE是否读取其他事务提交添加后的数据,解决幻影读问题

事务的传播行为:

级别行为
REQUIRED如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
SUPPORTS支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER以非事务方式运行,如果当前存在事务,抛出异常
NESTED如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作

2.3 TransactionStatus

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

  • 刷新事务
    void flush()
  • 获取是否存在存储点
    boolean hasSavepoint()
  • 获取事务是否完成
    boolean isCompleted()
  • 获取事务是否为新的事务
    boolean isNewTransaction()
  • 获取事务是否回滚
    boolean isRollbackOnly()
  • 设置事务回滚
    void setRollbackOnly()

2.4 spring中基于xml的声明式事务控制

代码–>github

  • 配置事务管理器
<!--    1.配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
  • 配置事务的通知,同时配置事务属性:需要导入事务的约束(tx和aop)
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

事务的属性:
isolation:用于指定事务的隔离级别,默认default,表示使用数据库的默认隔离级别
propagation:用于指定事务的传播行为,默认值是REQUIRED,表示一定会有事务
read-only:用于指定事务是否只读,只有查询方法才能设置为true,默认值是false;
timeout:用于指定事务的超时时间,默认值是-1,表示永不超时,设置单位为秒
no-rollback-for:用于指定一个异常,当产生该异常时,事务回滚,其他异常不回滚,默认任何异常都回滚
roolback-for:用于指定一个异常,当产生该异常时,事务不回滚,其他异常回滚,默认任何异常都回滚

<!--    2.配置事务的通知:需要导入事务的约束(tx和aop) ↑-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        5.配置事务的属性-->
        <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中的通用切入点表达式 并 建立事务通知和切入点表达式的对应关系
<!--    3.配置aop中的通用切入点表达式-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.wxy.service.impl.*.*(..))"/>
<!--        4.建立事务通知和切入点表达式的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
</beans>

2.5 spring中基于注解的声明式事务控制

代码-> github

  • 添加约束
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
  • 一些基础的配置
<!--    配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.wxy"></context:component-scan>
<!--    配置JdbcTemplate-->
    <bean id="jdbcTemplate" 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/testspring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
  • 配置事务管理器
<!--    1.配置事务管理器-->
    <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>
  • 在需要事务支持的地方使用@Transactional注解(注解的属性和xml的属性相同)
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class AccountSetviceImpl implements IAccountService {
 	 //---方法-----


    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public void transfer(String sourceName, String targetName, float money) {
		//---TODO
	}
}

2.6 spring中纯注解实现声明式事务控制

代码->github

  • 注解开启声明式事务
@EnableTransactionManagement

2.7 spring的编程式事务控制

动态代理,由spring写好环绕通知。

很少使用
传送门

3 spring5 新特性

3.1 与JDK相关的升级

基于JDK8编写,所以JDK8以下的无法使用

  • 速度提高了
    在这里插入图片描述
  • @NonNull 注解和@Nullable 注解的使用
    用 @Nullable 和 @NotNull 注解来显示表明可为空的参数和以及返回值。这样就够在编译的时候处理空值而不是在运行时抛出 NullPointerExceptions。
  • 日志记录方面
    Spring Framework 5.0 带来了 Commons Logging 桥接模块的封装, 它被叫做 spring-jcl 而不是标准的 Commons Logging。当然,无需任何额外的桥接,新版本也会对 Log4j 2.x, SLF4J, JUL ( java.util.logging) 进行自动检测。

3.2 核心容器的更新

在这里插入图片描述

3.3 JetBrains/ Kotlin语言支持

  • Kolin概述:是一种支持函数式编程编程风格的面向对象语言。Kotlin 运行在 JVM 之上,但运行环境并不限于 JVM。

3.4 响应式编程风格

在这里插入图片描述

3.5 Junit5支持

在这里插入图片描述

3.6 依赖库的更新

终止支持的依赖库:

  • Portlet.
  • Velocity.
  • JasperReports.
  • XMLBeans.
  • JDO.
  • Guava.

支持的类库:

  • Jackson 2.6+
  • EhCache 2.10+ / 3.0 GA
  • Hibernate 5.0+
  • JDBC 4.0+
  • XmlUnit 2.x+
  • OkHttp 3.x+
  • Netty 4.1+
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值