一,JdbcTemplate概述
JdbcTemplate是Spring框架提供的一个对JDBC封装的ORM对象模式,是对原始繁琐的Jdbs API对象的简单封装,Spring框架为我们提供了很多的操作模板类,例如:操作关系型数据库的JdbcTemplate,操作非关系型数据库的RedisTemplate
JdbcTemplate本质上并不能算一个完整独立的框架,它是一个Spring对JDBC的进一层的封装, 它只能内嵌在Spring中进行使用并不能独立出来使用
JdbcTemplate在数据持久层的使用基本上是没有的,已经被Mybatis基本垄断了,主要是学习使用,它有一个巨大的好处就是原始支持Spring AOP的声名式事务
一,JdbcTemplate和Mybatis的对比
两者的相同点:
- 底层都使用JDBC规范对数据库进行连接
- 采用ORM(对象关系映射)模型作为架构
- 都提供一系列的模板方法,提高了开发效率
两者的差异:
- 缓存支持:JdbcTemplate不支持sql数据缓存,Mybatis支持多个多级缓存
- 代码生成:JdbcTemplate没有代码生成的功能,Mybatis可以提供逆向工程进行代码和SQL的生成
- 动态和复杂SQL:JdbcTemplate不支持动态SQL,对复杂SQL的编写也不是很友好,Mybatis支持动态SQL且可以通过分步查询简化SQL的复杂度
- SQL可维护性:JdbcTemplate将SQL硬编码在java代码中,不利于维护,Mybatis将分主配置文件和映射配置文件,SQL静态化在xml文件中
- 声明式事务支持:JdbcTemplate原生就支持spring的声明式事务,Mybatis使用需要单独配置
- 框架的完整性:JdbcTemplate只是Spring一个ORM对象模型,内嵌spring使用,并不是完整意义上的框架,Mybatis是一个独立框架,可以进行独立使用
二,JdbcTemplate的开发过程
开发过程分四步:
- 导入maven依赖
- 配置连接池的DataSource
- 配置JdbcTemplate
- 使用JdbcTemplate进行操作
1,导入maven依赖
- mysql-connector-java:mysql连接
- spring-jdbc:spring操作JDBC,也就是JdbcTemplate的核心
- spring-tx:spring事务操作依赖
- spring-orm:spring整合mybatis和template需要这个依赖
- druid:数据库连接池,通过连接池创建DataSource对象
- Spring-context:spring的核心,它可以导入bean,context,aop,core,expression
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.0</version>
</dependency>
2,配置连接池的DataSource
jdbc.properties
username=root password=123 url=jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC drive=com.mysql.jdbc.Driver
1,注解配置DataSource(使用druid连接池创建)
@PropertySource(value = "classpath:/mysql.properties")//映入外部配置文件
@ComponentScan("com.component")
@Configuration
public class datasource_config {
@Value("${username}")
String username;
@Value("${password}")
String password;
@Value("${url}")
String url;
@Value("drive")
String drive;
@Bean
public DataSource get_datasource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setDriverClassName(drive);
return dataSource;
}}
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--引入配置文件-->
<context:property-placeholder location="mysql.properties"/>
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="name" value="${username}"/>
<property name="password" value="${password}"/>
<property name="url" value="${url}"/>
<property name="driver" value="${drive}"/>
</bean>
</beans>
3,配置JdbcTemplate
1,注解配置jdbctemplate
@Component
public class template {
@Autowired
DataSource dataSource;
public JdbcTemplate get_jdbctemplate(){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}}
2,xml配置jdbctemplate
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"/>
</bean>
4,使用JdbcTemplate进行操作
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = datasource_config.class)
public class test {
@Autowired
template jdbcTemplate;
@Test
public void test(){
JdbcTemplate jdbctemplate = jdbcTemplate.get_jdbctemplate();
int update = jdbctemplate.update("insert into jdbctemplatetest values (2,?,?)", "WQL", 21);
System.out.println(update);
}
}
三,JdbcTemplate的添加操作
jdbctemplate添加使用jdbcTemplate.update方法
它的重载方法:
- update(String var1)
- update(String var1, @Nullable Object... var2)
- update(String var1, Object[] var2, int[] var3)
参数:
- Object... var2:可变参数
- Object[] var2:值数值
- String var1:sql
注:返回值为int为影响的行数
在sql中?表示占为符,底层封装了properstatment
例:
① 实体映射类
public class jdbctemplatetest {
int id;
String name;
int age;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "jdbctemplatetest{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}}
② dao
@Repository
public class add_service implements add_service_in {
//注入JdbcTemplate
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public int update(jdbctemplatetest template) {
//写法一
int seccuss= jdbcTemplate.update("insert into jdbctemplatetest values (?,?,?)",template.getId(),template.getName(),template.getAge());
//写法二
Object[] value = {template.getId(),template.getName(),template.getAge()};
jdbcTemplate.update("insert into jdbctemplatetest values (?,?,?)",value);
return seccuss;
}
}
③ 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring.xml"})
public class test {
@Autowired
add_service dao;
@Test
public void test(){
jdbctemplatetest jdbctemplatetest = new jdbctemplatetest();
jdbctemplatetest.setId(3);
jdbctemplatetest.setName("FQ");
jdbctemplatetest.setAge(100);
dao.update(jdbctemplatetest);
}
四,JdbcTemplate的修改删除操作
@Repository
public class add_service implements add_service_in {
@Autowired
JdbcTemplate jdbcTemplate;
//更新
@Override
public int alter(jdbctemplatetest template) {
String sql = "update jdbctemplatetest set name=?,age=? where id=?";
Object[] val ={template.getName(),template.getAge(),template.getId()};
int a = jdbcTemplate.update(sql,val);
return a;
}
//删除
@Override
public int delete(jdbctemplatetest template) {
String sql = "delete from jdbctemplatetest where id=?";
int i = jdbcTemplate.update(sql, template.getId());
return i;
}
}
}
③ 测试
@Test
public void alter(){
jdbctemplatetest jdbctemplatetest = new jdbctemplatetest();
jdbctemplatetest.setId(1);
jdbctemplatetest.setName("FQ");
jdbctemplatetest.setAge(18);
int alter = dao.alter(jdbctemplatetest);
System.out.println(alter);
}
@Test
public void delete(){
jdbctemplatetest jdbctemplatetest = new jdbctemplatetest();
jdbctemplatetest.setId(2);
int delete = dao.delete(jdbctemplatetest);
System.out.println(delete);
}
五,JdbcTemplate的查询
JdbcTemplate查询和其他框架查询一样分了多种形式:
- 查询返回单个数值
- 查询返回对象
- 查询返回集合
JdbcTemplate通过query等方法进行查询:
- queryForObject(String sql, Class<T> requiredType, @Nullable Object... args):这个方法主要查询当个数值和对象
- query(String sql, ResultSetExtractor<T> var2):这个对象是通用的
- queryForList(String sql, Class<T> var2, @Nullable Object... var3):查询返回list集合
- queryForMap(String sql, @Nullable Object... var2):查询返回map集合
参数:
- String sql:sql语句
- Class<T> var2:指定返回的数据类型或对象类型或集合中的数据类型
- Object... var:占位符数据
一,查询返回当个数值
① 映射类(和之前是一样的)
② 查询
@Repository
public class select_dao implements select_dao_in {
@Autowired
JdbcTemplate jdbcTemplate;
//查询返回单个值
@Override
public int query_int() {
String SQL = "select count(*) from jdbctemplatetest";
Integer integer = jdbcTemplate.queryForObject(SQL, Integer.class);
return integer;
}}
③ 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring.xml"})
public class test1 {
@Autowired
select_dao selectDao;
@Test
public void query_value(){
int i = selectDao.query_int();
System.out.println(i);
}}
二,查询返回对象
② 查询
//查询返回对象
@Override
public jdbctemplatetest queue_bean(int id) {
String SQL = "select * from jdbctemplatetest where id=?";
jdbctemplatetest object = jdbcTemplate.queryForObject(SQL, jdbctemplatetest.class, id);
return object;
}
@Test
public void query_bean(){
jdbctemplatetest queue_bean = selectDao.queue_bean(1);
System.out.println(queue_bean);
}
三,查询返回集合
② 查询
//查询返回集合
@Override
public List<jdbctemplatetest> queue_list() {
String SQL = "select * from jdbctemplatetest";
//写法一
jdbcTemplate.queryForList(SQL, jdbctemplatetest.class);
//写法二
List<jdbctemplatetest> jdbctemplatetestslist = jdbcTemplate.query(SQL,new BeanPropertyRowMapper<jdbctemplatetest>(jdbctemplatetest.class));
return jdbctemplatetestslist;
}
@Test
public void query_list(){
List<jdbctemplatetest> list = selectDao.queue_list();
System.out.println(list);
}
六,JdbcTemplate批量操作
JdbcTemplate支持批量增加,修改,删除操作
增加,修改,删除操作使用是jdbcTemplate.update方法,批量增加,修改,删除操作使用的是jdbcTemplate.batchUpdate()方法
jdbcTemplate.batchUpdate()方法参数:
- String sql:SQL语句
- List<Object[]>:list集合,添加多条记录
@Override
public int[] add_batch(List<Object[]> value) {
String SQL = "insert into jdbctemplatetest values(?,?,?)";
int[] ints = jdbcTemplate.batchUpdate(SQL, value);
return ints;
}
@Override
public int[] alter_batch(List<Object[]> value) {
String SQL = "update jdbctemplatetest set name=?,age=? where id=?";
int[] ints = jdbcTemplate.batchUpdate(SQL, value);
return ints;
}
@Override
public int[] delete_batch(List<Object[]> value) {
String SQL = "update jdbctemplatetest set name=?,age=? where id=?";
int[] ints = jdbcTemplate.batchUpdate(SQL, value);
return ints;
}






Comments | NOTHING