JdbcTemplate基本使用
1-JdbcTemplate基本使用-概述(了解)
JdbcTemplate是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供
了很多的操作模板类。例如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosql数据库的
RedisTemplate,操作消息队列的JmsTemplate等等。
2-JdbcTemplate基本使用-开发步骤(理解)
①导入spring-jdbc和spring-tx坐标
②创建数据库表和实体
③创建JdbcTemplate对象
④执行数据库操作
3-JdbcTemplate基本使用-快速入门代码实现(应用)
导入spring-jdbc和spring-tx坐标
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring‐context</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring‐test</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring‐jdbc</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring‐tx</artifactId> <version>5.2.8.RELEASE</version> </dependency> <!‐‐织入包‐‐> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.4</version> </dependency> <!‐‐数据源相关‐‐> <!‐‐ Druid连接池 ‐‐> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!‐‐ mysql驱动 ‐‐> <dependency> <groupId>mysql</groupId> <artifactId>mysql‐connector‐java</artifactId> <version>5.1.39</version> </dependency> <!‐‐servlet相关‐‐> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet‐api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp‐api</artifactId> <version>2.2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
创建数据库表和实体
DROP TABLE IF EXISTS account; CREATE TABLE account ( id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(50) NOT NULL, money DOUBLE NOT NULL ); INSERT INTO account VALUES (NULL,'旺财',1000); INSERT INTO account VALUES (NULL,'小强',1000); SELECT * FROM account;
package com.summer.domain;
public class Account {
private int id;
private String name;
private double money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
创建JdbcTemplate对象
执行数据库操作
//测试JdbcTemplate的开发步骤
@Test
public void test1(){
//创建数据源
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
//创建 模板对象
JdbcTemplate template = new JdbcTemplate();
//设置数据源
template.setDataSource(dataSource);
//执行更新操作 (添加 修改 删除)
int i = template.update("INSERT INTO account VALUES (NULL,?,?);", "如花", 1000);
System.out.println(i);
}
4-JdbcTemplate基本使用-spring产生模板对象分析(理解)
我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部
将数据源DataSource注入到JdbcTemplate模版对象中,然后通过Spring容器获得JdbcTemplate对象来执行操作
5-JdbcTemplate基本使用-spring产生模板对象代码实现(应用)
配置如下:
<!‐‐配置数据源 将数据的创建 交给spring容器‐‐> <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!‐‐创建 jdbc模板对象‐‐> <bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"> <!‐‐配置数据源‐‐> <property name="dataSource" ref="dataSource" /> </bean>
测试代码
//将spring和 junit整合s
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateTest {
@Autowired
private JdbcTemplate jdbcTemplate;
//测试spring管理 JdbcTemplate
@Test
public void test2(){
int i = jdbcTemplate.update("INSERT INTO account VALUES (NULL,?,?);", "秋香", 1000);
System.out.println(i);
}
}
6-JdbcTemplate基本使用-spring产生模板对象代码实现
将数据库的连接信息抽取到外部配置文件中,和spring的配置文件分离开,有利于后期维护
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root
配置文件修改为:
<?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"
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
">
<!‐‐加载properties配置文件‐‐>
<context:property‐placeholder location="classpath:jdbc.properties"/>
<!‐‐配置数据源 将数据的创建 交给spring容器‐‐>
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!‐‐创建 jdbc模板对象‐‐>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<!‐‐配置数据源‐‐>
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
7-JdbcTemplate基本使用-常用操作-更新操作(应用)
//将spring和 junit整合s
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
//注入jdbc模板
@Autowired
private JdbcTemplate jdbcTemplate;
//测试修改操作
@Test
public void testUpdate(){
jdbcTemplate.update("update account set money = ? where id = ?;",800,1);
}
//测试删除
@Test
public void testDelete(){
jdbcTemplate.update("DELETE from account where id = ?",1);
}
}
8-JdbcTemplate基本使用-常用操作-查询操作(应用)
package com.summer.test;
import com.summer.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
//将spring和 junit整合s
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
//注入jdbc模板
@Autowired
private JdbcTemplate jdbcTemplate;
//测试修改操作
@Test
public void testUpdate(){
jdbcTemplate.update("update account set money = ? where id = ?;",800,1);
}
//测试删除
@Test
public void testDelete(){
jdbcTemplate.update("DELETE from account where id = ?",1);
} /
/聚合查询
@Test
public void testQueryCount(){
Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
System.out.println(count);
} /
/查询一个
@Test
public void testQueryOne(){
Account account = jdbcTemplate.queryForObject("select * from account where name=?", new
BeanPropertyRowMapper<Account>(Account.class), "旺财");
System.out.println(account);
} /
/查询所有
@Test
public void testQueryAll(){
List<Account> accountList = jdbcTemplate.query("select * from account", new
BeanPropertyRowMapper<Account>(Account.class));
System.out.println(accountList);
}
}
9-JdbcTemplate基本使用-知识要点(理解,记忆)
①导入spring-jdbc和spring-tx坐标
②创建数据库表和实体
③创建JdbcTemplate对象
JdbcTemplate jdbcTemplate = newJdbcTemplate(); jdbcTemplate.setDataSource(dataSource);
④执行数据库操作
更新操作:
jdbcTemplate.update (sql,params)
查询操作:
jdbcTemplate.query (sql,Mapper,params)
jdbcTemplate.queryForObject(sql,Mapper,params)
声明式事务控制
1.事务的概念
概念:
事务是一组操作的执行单元,相对于数据库操作来讲,事务管理的是一组SQL指令,比如增加,修改,删除等,事
务的一致性,要求,这个事务内的操
作必须全部执行成功,如果在此过程种出现了差错,比如有一条SQL语句没有执行成功,那么这一组操作都将全部
回滚。
仅用四个词解释事务(ACID)
1.atomic(原子性):要么都发生,要么都不发生。
2.consistent(一致性):数据应该不被破坏。
3.Isolate(隔离性):用户间操作不相混淆
4.Durable(持久性):永久保存,例如保存到数据库中等
2 .基于注解的声明式事务控制
2.1 什么是声明式事务控制
Spring 的声明式事务顾名思义就是采用声明的方式来处理事务。这里所说的声明,就是指在配置文件中声明,用在Spring 配置文件中声明式的处理事务来代替代码式的处理事务
声明式事务处理的作用
- 事务管理不侵入开发的组件。具体来说,业务逻辑对象就不会意识到正在事务管理之中,事实上也应该如此,因为事务管理是属于系统层面的服务,而不是业务逻辑的一部分,如果想要改变事务管理策划的话,也只需要在定义文件中重新配置即可
- 在不需要事务管理的时候,只要在设定文件上修改一下,即可移去事务管理服务,无需改变代码重新编译,这样维护起来极其方便
注意:Spring 声明式事务控制底层就是AOP。
引入aop、tx命名空间
<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">
2.2 使用注解配置声明式事务控制
编写 AccoutDao
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void out(String outMan, double money) {
jdbcTemplate.update("update account set money=money‐? where name=?",money,outMan);
}
public void in(String inMan, double money) {
jdbcTemplate.update("update account set money=money+? where name=?",money,inMan);
}
}
2.编写 AccoutService
@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
public void transfer(String outMan, String inMan, double money) {
accountDao.out(outMan,money);
int i = 1/0;
accountDao.in(inMan,money);
}
}
编写 applicationContext.xml 配置文件
<!‐‐之前省略datsSource、jdbcTemplate‐‐> <!‐‐平台事务管理器‐‐> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!‐‐事务的注解驱动‐‐> <tx:annotation‐driven/>
2.3 注解配置声明式事务控制解析
① 使用 @Transactional 在需要进行事务控制的类或是方法上修饰,注解可用的属性同 xml 配置方式,例如隔离级别、传播行为等。
②注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置。
③使用在方法上,不同的方法可以采用不同的事务参数配置。
④ Xml 配置文件中要开启事务的注解驱动 <tx:annotation-driven />
2.4 知识要点
注解声明式事务控制的配置要点
- 事务通知的配置 (
@Transactional注解配置 ) - 事务注解驱动的配置
<tx:annotation-driven/>
到此这篇关于超细致讲解Spring框架 JdbcTemplate的使用的文章就介绍到这了,更多相关Spring JdbcTemplate内容请搜索好代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好代码网!




