1.JdbcTemplate简单使用

1.1.引入相关依赖包

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>

1.2.创建spring配置

@Configuration
@ComponentScan({"ox"})
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration { // 1.数据连接信息
// jdbc.properties不能使用username这个key.spring占用了,所以要加前缀
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password; /**
* 2.创建数据源
*/
@Bean
public ComboPooledDataSource comboPooledDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
} /**
* 3.创建jdbcTemplate
* 方法形参 自动注入
*/
@Bean
public JdbcTemplate jdbcTemplate(ComboPooledDataSource comboPooledDataSource){
return new JdbcTemplate(comboPooledDataSource);
}
}

1.3.jdbcTemplate使用

a.聚合查询

@Test
public void t01(){
Long count = jdbcTemplate.queryForObject(
"select count(*) from account",
Long.class);
System.out.println("数据库有"+count+"条数据!");
}

b.查询单个数据

@Test
public void t02(){
Account account = jdbcTemplate.queryForObject(
"select * from account where name=?",
new BeanPropertyRowMapper<Account>(Account.class),
"张三");
System.out.println(account);
}

c.查询多个

@Test
public void t03(){
List<Account> accountList = jdbcTemplate.query(
"select * from account",
new BeanPropertyRowMapper<Account>(Account.class)); for (Account account : accountList) {
System.out.println(account);
}
}

d.插入

@Test
public void t04(){
Account account = new Account();
account.setName("王五");
account.setMoney(19.1d);
int update = jdbcTemplate.update(
"insert into account values(?,?)",
account.getName(),
account.getMoney()); System.out.println(update > 0 ? "success" : "fail");
}

e.修改

@Test
public void t05(){
int update = jdbcTemplate.update(
"update account set money = 100 where name = ?",
"王五"); System.out.println(update > 0 ? "success" : "fail");
}

f.删除

@Test
public void t06(){
int flag = jdbcTemplate.update(
"delete from account where name =?",
"王五"); System.out.println(flag > 0 ? "success" : "fail");
}

2.声明式事务

2.1.简述

2.2.相关对象

2.2.1.PlatformTransactionManager

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

一般使用实现类DataSourceTransactionManager或HibernateTransactionManager

2.2.2.TransactionDefinition

TransactionDefinition 是事务的定义信息对象.定义了事务的隔离级别和传播行为

2.2.3.TransactionStatus

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

2.3 事务隔离级别

设置隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读和虚读。

  • ISOLATION_DEFAULT
  • ISOLATION_READ_UNCOMMITTED
  • ISOLATION_READ_COMMITTED
  • ISOLATION_REPEATABLE_READ
  • ISOLATION_SERIALIZABLE

2.4 事务传播行为

  • REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
  • SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
  • MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
  • REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
  • NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
  • NEVER:以非事务方式运行,如果当前存在事务,抛出异常
  • NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作
  • 超时时间:默认值是-1,没有超时限制。如果有,以秒为单位进行设置
  • 是否只读:建议查询时设置为只读

2.5.基于xml的声明式事务

2.5.1.什么时声明式事务

是什么:在配置文件中声明,用在 Spring 配置文件中声明式的处理事务来代替代码式的处理事务。

作用:事务管理不侵入开发的组件

底层:Spring 声明式事务控制底层就是AOP

2.5.2.配置实现

<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <!--事务增强配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice> <!--事务的aop增强-->
<aop:config>
<aop:pointcut id="myPointcut" expression="execution(* xxx.yyy.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"></aop:advisor>
</aop:config>

2.5.3.切点方法的事务参数的配置

<!--事务增强配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>

其中,tx:method 代表切点方法的事务参数的配置,例如:

<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>
  • name:切点方法名称
  • isolation:事务的隔离级别
  • propogation:事务的传播行为
  • timeout:超时时间
  • read-only:是否只读

2.6.基于注解的声明式事务

2.6.1.使用步骤

a.在需要事务控制的类或方法上添加@Transactional

b.在xml中开启事务的注解驱动

<tx:annotation-driven/>

2.6.2.@Transactional

  • 使用 @Transactional 在需要进行事务控制的类或是方法上修饰,注解可用的属性同 xml 配置方式,例如隔离级别、传播行为等。
  • 注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置。
  • 使用在方法上,不同的方法可以采用不同的事务参数配置。
  • Xml配置文件中要开启事务的注解驱动<tx:annotation-driven/>
  • 注解配置文件中开启事务注解驱动@EnableTransactionManagement

最新文章

  1. C++智能指针简单剖析
  2. sqlserver中的循环遍历(普通循环和游标循环)
  3. 如何一次把所有wordpress插件都禁用了
  4. linux笔记:shell基础-bash基本功能
  5. C#环境datagidview添加删除操作
  6. linux下调整音量大小
  7. SharePoint 2013 Nintex Workflow 工作流帮助(六)
  8. tcp断开的4次挥手
  9. Android系统Google Maps开发实例浅析
  10. Java面试题精选(二)线程编程、数据库理论和Jdbc部分
  11. ASP.NET MVC性能优化工具 MiniProfiler
  12. 转义字符(\)对JavaScript中JSON.parse的影响
  13. 《JavaScript DOM 编程艺术 》 笔记
  14. iOS应用的几个阶段
  15. 急!!ftp登录错误,提示 530 not logged in,连接失败 ,,是怎么回事啊
  16. HDU 4349 Xiao Ming&#39;s Hope [Lucas定理 二进制]
  17. typedef介绍
  18. sql 表值函数-将一个传入的字符串用2中分隔符拆分成临时表
  19. 基于sklearn和keras的数据切分与交叉验证
  20. es分词器

热门文章

  1. 007 GMII、SGMII和SerDes的区别和联系
  2. JVM快速扫盲篇
  3. Windows安装Linux虚拟机(CentOS7)
  4. 数学log的基本知识
  5. WPF---样式(一)
  6. win10下安装mysql5.7-建议安装-自定义位置
  7. 如何在指定的地址上创建C++对象
  8. mysql基础操作(三):数据约束
  9. 刷题-力扣-518. 零钱兑换 II
  10. 一文彻底弄懂this关键字用法