【Spring】模板JdbcTemplate + 事务管理


之前我们也有接触 Jdbc,进而让我们可以对数据库执行增删改查。而在Spring中,给我们提供了JdbcTemplate,从而使代码开销更小。

JdbcTemplate

1.1 配置

1.Mavan的pom.xml中配置jar包

<!--Jdbc模板-->
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.0.2.RELEASE</version>
  </dependency>
  
<!--MySQL驱动-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.47</version>
</dependency>
<!--C3P0连接池-->
<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.2</version>
</dependency>

2.自动注解方式配置Bean
Spring的day4jdbc.xml配置文件

<!-- 配置自动扫描的包 -->
<context:component-scan base-package="xu.day4.jdbc"></context:component-scan>

<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置 C3P0 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
    <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- 配置 Spirng 的 JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource">
</bean>
<!-- 配置 NamedParameterJdbcTemplate, 该对象可以使用具名参数, 其没有无参数的构造器, 所以必须为其构造器指定参数 -->
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg type="javax.sql.DataSource" ref="dataSource"/>
</bean>

1.2 常用方法

先给出用到的普通类的结构
在这里插入图片描述

ApplicationContext ctx = new ClassPathXmlApplicationContext("day4jdbc.xml");
AccountDao accountDao = ctx.getBean(AccountDao.class);

@Repository
public class AccountDao{
    
    
    @Autowired   //属性采取注入的方式,该类不能new 方式实例化,要不该属性为null
    private JdbcTemplate jdbcTemplate;

    //....方法

}

//常用方法
//执行 INSERT, UPDATE, DELETE
String sql = "update account set name=? where id =?";
jdbcTemplate.update(sql, "xu", 4);
/**
  * 执行批量更新: 批量的 INSERT, UPDATE, DELETE
  * 最后一个参数是 Object[] 的 List 类型: 因为修改一条记录需要一个 Object 的数组, 那么多条不就需要多个 Object 的数组吗
  */
String sql = "insert into account(id,name,balance) values(?,?,?)";
ArrayList<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(new Object[]{
    
    1, "哈哈哈", 2323});
batchArgs.add(new Object[]{
    
    2, "loulou", 2323});
jdbcTemplate.batchUpdate(sql, batchArgs);

 /**
  * 从数据库中获取一条记录, 实际得到对应的一个对象
  * 注意不是调用 queryForObject(String sql, Class<Employee> requiredType, Object... args) 方法!
  * 而需要调用 queryForObject(String sql, RowMapper<Employee> rowMapper, Object... args)
  * 1. 其中的 RowMapper 指定如何去映射结果集的行, 常用的实现类为 BeanPropertyRowMapper
  * 2. 若SQL字段名与类属性名不一致,可使用 SQL 中列的别名完成列名和类的属性名的映射. 例如 last_name lastName
  * 3. 不支持级联属性. JdbcTemplate 到底是一个 JDBC 的小工具, 而不是 ORM 框架
  */
String sql = "Select id,name,balance from account where id = ?";
BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
Account account = jdbcTemplate.queryForObject(sql, rowMapper, 1);
System.out.println(account);
System.out.println(accountDao.getJdbcTemplate());
// 获取单个列的值, 或做统计查询,使用 queryForObject(String sql, Class<Long> requiredType) 
String sql = "Select count(id) from account where id > ?";
long count = jdbcTemplate.queryForObject(sql, Long.class, 1);
System.out.println(count);

//查到实体类的集合,注意调用的不是 queryForList 方法
String sql = "Select id,name,balance from account where id > ?";
BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
List<Account> accounts = jdbcTemplate.query(sql, rowMapper, 5);
System.out.println(accounts);


 /**
  * 使用具名参数时, 可以使用 update(String sql, SqlParameterSource paramSource) 方法进行更新操作
  * 1. SQL 语句中的参数名和类的属性一致!
  * 2. 使用 SqlParameterSource 的 BeanPropertySqlParameterSource 实现类作为参数. 
  */
//NamedParameterJdbcTemplate namedJdbc = ctx.getBean(NamedParameterJdbcTemplate.class);
String sql = "insert into account(id,name,balance) values(:id,:name,:balance)";
Account account = new Account();
account.setId(3);
account.setName("青鸟飞羽");
account.setBalance(4832.0);
BeanPropertySqlParameterSource paramSource = new BeanPropertySqlParameterSource(account);
namedJdbc.update(sql, paramSource);

事务管理

只有公有方法才能通过Spring AOP进行事务管理

2.1 自动注解方式配置Bean

day4jdbc.xml

<context:component-scan base-package="xu.day4.tx"></context:component-scan>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 启用事务注解 --> <!-- 留意配置文件头部的引用约束是否正确 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

注意:
1.错误提示:通配符的匹配很全面, 但无法找到元素 ‘tx:annotation-driven’ 的声明
原因:.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:context="http://www.springframework.org/schema/context" 
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd			
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
...
</beans>       

java类
在这里插入图片描述

@Service
public class BookShopService {
    
    
    @Autowired
    private BookShopDao bookShopDao;
    //添加事务注解	
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void purchase(String username, String isbn) {
    
    
    	try {
    
    
   		Thread.sleep(5000); //单位毫秒
  	} catch (InterruptedException e) {
    
    }
  	
        int price = bookShopDao.getPrice(isbn); //1. 获取书的单价
        bookShopDao.updateBookNum(isbn); //2. 更新数的库存
        bookShopDao.updateBalance(username,price); //3. 更新用户余额
    }

}
@Service
public class Cashier {
    
    
    @Autowired
    private BookShopService bookShopService;

    @Transactional
    public void checkout(String userName, List<String> isbns) {
    
    
        for (String isbn : isbns) {
    
    
            bookShopService.purchase(userName,isbn);
        }
    }
}

☞注意①②③④⑤⑥×✔✘☞☜√
1.事务注解的参数:
@Transactional(propagation=Propagation.REQUIRES_NEW,
isolation=Isolation.READ_COMMITTED,
// noRollbackFor={UserAccountException.class}
readOnly=false,
timeout=3)
①使用 propagation 指定事务的传播行为, 即当前的事务方法被另外一个事务方法调用时,如何使用事务。
默认取值为 REQUIRED, 即使用调用方法的事务 ;REQUIRES_NEW: 事务自己的事务, 调用的事务方法的事务被挂起
②使用 isolation 指定事务的隔离级别, 最常用的取值为 READ_COMMITTED
③默认情况下 Spring 的声明式事务对所有的运行时异常进行回滚. 也可以通过对应的属性进行设置. 通常情况下去默认值即可. noRollbackFor指定一组异常类,遇到时不回滚 rollbackFor正好相反
④使用 readOnly 指定事务是否为只读. 表示这个事务只读取数据但不更新数据, 这样可以帮助数据库引擎优化事务. 若真的事一个只读取数据库值的方法, 应设置 readOnly=true
⑤使用 timeout 指定强制回滚之前事务可以占用的时间. 单位是秒

REQUIRED时在这里插入图片描述

REQUIRES_NEW时
在这里插入图片描述

2.2 xml配置配置文件方式

感觉相对自动注解麻烦了许多

<!-- 手动配置一些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="purchase" propagation="REQUIRES_NEW"/>
   <tx:method name="get*" read-only="true"/>
   <tx:method name="find*" read-only="true"/>
   <tx:method name="*"/>
  </tx:attributes>
 </tx:advice>
 
 <!-- 3. 配置事务切入点, 以及把事务切入点和事务属性关联起来 -->
 <aop:config>
  <aop:pointcut expression="execution(* com.atguigu.spring.tx.xml.service.*.*(..))" 
   id="txPointCut"/>
  <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> 
 </aop:config>

猜你喜欢

转载自blog.csdn.net/qq_40265247/article/details/106236208