Spring框架Day4--JdbcTemplate、Spring声明式事务管理

Spring框架

第四天:

任务:

  • Spring中JdbcTemplate

  • Spring声明式事务管理:基于注解、基于xml


Spring中JdbcTemplate:

本质:是框架提供的一个对象,对JDBC API对象进行薄薄的封装

位置:在spring-jdbc-x.x.x.RELEASE.jar中。除此之外还要导入spring-tx-x.x.x.RELEASE.jar(和事务相关的jar包)

实际作用:用于和数据库交互,实现对表的CRUD操作

jdbctemplate的CRUD操作:

增、删、改用update
查用query,注意query后的参数列表

        //执行操作(单表操作)
          //1 保存
          jt.update("insert into account(name,money) values(?,?)","eee",3333f);
          //2 更新
          jt.update("update account set name = ? where id =?","abc",1);
          //3 删除
          jt.update("delete from account where id = ?",11);
          //4 查询所有
          List<Account> accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),600f);
          for(Account account:accounts){
              System.out.println(account);
          }
          //5 查询一个
          List<Account> accounts1 = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);
          System.out.println(accounts1.isEmpty()?"无内容":accounts1.get(0));
          //6 查询返回一行一列(使用聚合函数,但不加group by子句)
           int a = jt.queryForObject("select count(*) from account where money > ?",Integer.class,600f);//第二个参数代表输出值的类型(强转)
        System.out.println(a);

平常的CRUD都是基于dao的,则首先需要在dao中有JdbcTemplate对象及其set方法【便于xml配置ioc】。

但如果有很多dao,每个都要写一遍这两行则又会产生代码冗余,此处推荐直接继承JdbcDaoSupport类,在方法中凡是用到了JdbcTemplate对象的地方都可以直接调用其方法,并且此处super都可省略。

注意:如果不继承(麻烦点多写两行)则可以自由选择注解/xml方式的ioc注入对象;如果继承,JdbcDaoSupport类是封装在jar包中的只读文件,所以只能通过xml方式进行注入。

package com.itheima.dao.impl;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
//用xml方式-> extends JdbcDaoSupport (此类含有所有dao都需要的以下代码,为了减少重复代码,可以继承使用)
//   private JdbcTemplate jdbcTemplate;
//   public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
//       this.jdbcTemplate = jdbcTemplate;
//   }

    public Account findAccountByID(Integer accountId) {
        List<Account> accountList = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        return accountList.isEmpty()?null:accountList.get(0);
    }

    public Account findAccountByName(String accountName) {
        List<Account> accountList = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
        if(accountList.isEmpty())
            return null;
        if(accountList.size() > 1)
            throw new RuntimeException("结果不唯一");
        return accountList.get(0);
    }

    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name = ?,money = ? where id= ?",account.getName(),account.getMoney(),account.getId());
    }
}

Spring基于xml的声明式事务控制

步骤:

0. 首先导入依赖:xmlns:tx
1. 1.配置事务管理器(spring中已经有了,不需要再自己手写->详见第三天中的两个工具类)
2.配置事务的通知
     此时需要导入事务的约束 tx名称空间和约束 同时也需要aop的
     使用tx:advice标签配置事务通知
     属性:id:给事务通知起一个唯一标识
           transactionManager:给事务通知提供一个事务管理器引用
3.配置aop中的通用切入点表达式
4.建立事务通知和切入点表达式的对应联系
5.配置事务的属性:在事务的通知tx:advice标签内部配置
    isolation:事务的隔离级别 默认值:DEFAULT 表示使用数据库的默认隔离级别
    timeout:事务的超时时间 默认值:-1 表示永不超时 如果指定数值则以秒为单位
    propagation:事务的传播行为 默认值:REQUIRED 表示一定会有事务 增删改的选择 查询方法可以选择SUPPORTS
    read-only:事务是否只读 只有查询才设置为true 否则为false 表示读写
    rollback-for:指定一个异常,当产生该异常时事务回滚;产生其他异常时,事务不回滚;无默认值表示任何异常都回滚
    no-rollback-for:指定一个异常,当产生该异常时,事务不回滚;产生其他异常时,事务回滚;无默认值,表示任何异常都回滚【无默认值情况下同上】

bean.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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">

    <!--配置账户的持久层-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="datasource"></property>
    </bean>

    <!--配置业务层-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></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/spring?serverTimezone=GMT%2B8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="cherrymjy0409"></property>
    </bean>
    
    <!-------------------------------------以下是是重点--------------------------------------------->
    <!--1.配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>
    <!--2.配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/><!--这行优先级比上一行高,前提是所有查询方法起名规范-->
        </tx:attributes>
    </tx:advice>
    <!--3.配置aop-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
</beans>

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

bean.xml被掏空:(记得修改依赖)

<?xml version="1.0" encoding="UTF-8"?>
<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
        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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></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/****"></property>
        <property name="username" value="****"></property>
        <property name="password" value="****"></property>
    </bean>

    <!-- spring中基于注解 的声明式事务控制配置步骤
        1、配置事务管理器
        2、开启spring对注解事务的支持
        3、在需要事务支持的地方使用@Transactional注解
     -->
    <!-- 配置事务管理器 -->
    <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>
</beans>

在dao层加上@Component和@Autowired,此处将展开service层的改动:

AccountServiceImpl.java:

@Transactional() 单一个标签就取代了原来xml中的好几行。但是!对于不同情况的属性需要在用的时候注明(propagation= Propagation.SUPPORTS,readOnly=true vs propagation= Propagation.REQUIRED,readOnly=false)

注解方法在这里就容易有遗漏出错,故在声明式事务控制中推荐xml方法。

package com.itheima.service.impl;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
 * 账户的业务层实现类
 * 事务控制应该都是在业务层
 */
 
@Service("accountService")
@Transactional(propagation= Propagation.SUPPORTS,readOnly=true)//只读型事务的配置
public class AccountServiceImpl implements IAccountService{
    @Autowired
    private IAccountDao accountDao;
    
    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    //需要的是读写型事务配置
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false)
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
            //2.1根据名称查询转出账户
            Account source = accountDao.findAccountByName(sourceName);
            //2.2根据名称查询转入账户
            Account target = accountDao.findAccountByName(targetName);
            //2.3转出账户减钱
            source.setMoney(source.getMoney()-money);
            //2.4转入账户加钱
            target.setMoney(target.getMoney()+money);
            //2.5更新转出账户
            accountDao.updateAccount(source);
            int i=1/0;
            //2.6更新转入账户
            accountDao.updateAccount(target);
    }
}

结束 !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不试一下怎么知道我不行?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值