简介;

  JdbcTemplate是Spring提供的一套JDBC模板框架,利用AOP技术解决直接使用JDBC带来的重复代码问题。它没有MyBatis使用那么灵活,但是却比直接使用JDBC方便得多。SpringBoot中对JdbcTemplate的使用提供了自动化配置类JdbcTemplateAutoConfiguration

  部分源码:

@Configuration
@ConditionalOnClass({DataSource.class, JdbcTemplate.class})
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
@EnableConfigurationProperties({JdbcProperties.class}) public class JdbcTemplateAutoConfiguration {
public JdbcTemplateAutoConfiguration() {
}
@Configuration
static class JdbcTemplateConfiguration {
private final DataSource dataSource;
private final JdbcProperties properties; JdbcTemplateConfiguration(DataSource dataSource, JdbcProperties properties) {
this.dataSource = dataSource;
this.properties = properties;
} @Bean
@Primary
@ConditionalOnMissingBean({JdbcOperations.class})
public JdbcTemplate jdbcTemplate() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
Template template = this.properties.getTemplate();
jdbcTemplate.setFetchSize(template.getFetchSize());
jdbcTemplate.setMaxRows(template.getMaxRows());
if (template.getQueryTimeout() != null) {
jdbcTemplate.setQueryTimeout((int)template.getQueryTimeout().getSeconds());
} return jdbcTemplate;
} }

  当classpath下存在DataSource和JdbcTemplate并且DataSource只有一个实例时,自动配置才会生效,若开发者没有提供JdbcOperations,则SpringBoot会自动向容器中注入一个JdbcTemplate(是JdbcOperations的子类)。

  我们自己想用JdbcTemplate时,只需要提供JdbcTemplateDataSource即可。

使用

  1.建表,插入数据  

  2.pom.xml

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>

3.application.properties

4.实体类

5.Dao------》增+改+删+查+查询所有

@Repository
public class BookDao {

@Autowired
JdbcTemplate jdbcTemplate;
public int addBook(Book book) {
return jdbcTemplate.update("INSERT INTO book(name,author) VALUES (?,?)",
book.getName(), book.getAuthor());
}

public int updateBook(Book book) {
return jdbcTemplate.update("UPDATE book SET name=?,author=? WHERE id=?",
book.getName(), book.getAuthor(), book.getId());
}

public int deleteBookById(Integer id) {
return jdbcTemplate.update("DELETE FROM book WHERE id=?", id);
}

public Book getBookById(Integer id) {
return jdbcTemplate.queryForObject("select * from book where id=?",
new BeanPropertyRowMapper<>(Book.class), id);
}

public List<Book> getAllBooks() {
return jdbcTemplate.query("select * from book",
new BeanPropertyRowMapper<>(Book.class));
}
}

  注意到上面,前三种都是update方法,jdbctemplate中增删改主要使用update和batchUpdate批处理方法,查询由query和queryForObject完成,此外execute方法可以用来执行任意的SQL,call方法执行存储过程等等自己可以了解。

6.Service层和Controller层

@Service
public class BookService {
@Autowired
BookDao bookDao;
public int addBook(Book book) {
return bookDao.addBook(book);
}
public int updateBook(Book book) {
return bookDao.updateBook(book);
}
public int deleteBookById(Integer id) {
return bookDao.deleteBookById(id);
}
public Book getBookById(Integer id) {
return bookDao.getBookById(id);
}
public List<Book> getAllBooks() {
return bookDao.getAllBooks();
}
}
@RestController
public class BookController {

@Autowired
BookService bookService;

@GetMapping("/bookOps")
public void bookOps() {
Book b1 = new Book();
b1.setId(99);
b1.setName("西厢记");
b1.setAuthor("王实甫");
int i = bookService.addBook(b1);
System.out.println("addBook>>>" + i);
Book b2 = new Book();
b2.setId(1);
b2.setName("朝花夕拾");
b2.setAuthor("鲁迅");
int updateBook = bookService.updateBook(b2);
System.out.println("updateBook>>>"+updateBook);

Book b3 = bookService.getBookById(1);
System.out.println("getBookById>>>"+b3);
int delete = bookService.deleteBookById(2);
System.out.println("deleteBookById>>>"+delete);

List<Book> allBooks = bookService.getAllBooks();
System.out.println("getAllBooks>>>"+allBooks);
}
}

访问http://localhost:8080/bookOps

SpringBoot整合持久层技术--(一)JdbcTemplate的更多相关文章

  1. SpringBoot整合持久层技术--(三)Spring Data JPA

    简介: JPA(java Persistence API)和SpringData是两个范畴的概念.spring data jpa是spring公司下的spring data项目的一个模块. sprin ...

  2. SpringBoot整合持久层技术--(二)MyBatis

    简介: 原名iBatis,SpringBoot中使用MyBatis: pom.xml <dependency> <groupId>org.springframework.boo ...

  3. SpringBoot整合持久层技术-创建项目

    新建项目 Pom.xml文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns=&q ...

  4. springboot整合持久层技术(mysql驱动问题)

    java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more tha ...

  5. SpringBoot_整合视图层技术

    SpringBoot整合视图层技术 在目前的企业级应用开发中,前后端分离是趋势,但是视图层技术还占有一席之地.Spring Boot对视图层技术提供了很好的支持,官方推荐使用的模板引擎是Thymele ...

  6. 【Spring】对持久层技术的整合

    一.持久层技术 二.JdbcTemplate 开发步骤: 1. 导入相关的jar包 2. 配置连接池(数据源) 将参数设置到属性文件中: 3. 创建表 4. 编写实体类 5. Dao层实现 5.1 继 ...

  7. Spring Boot 整合视图层技术

    这一节我们主要学习如何整合视图层技术: Jsp Freemarker Thymeleaf 在之前的案例中,我们都是通过 @RestController 来处理请求,所以返回的内容为json对象.那么如 ...

  8. Spring Boot 整合视图层技术,application全局配置文件

    目录 Spring Boot 整合视图层技术 Spring Boot 整合jsp Spring Boot 整合freemarker Spring Boot 整合视图层技术 Spring Boot 整合 ...

  9. SpringBoot持久层技术

    一.Springboot整合mybatis maven中添加对数据库与mybatis的依赖 <dependencies> <dependency> <groupId> ...

随机推荐

  1. 《剑指Offer》第二章(一)题 9 -12

    第二章 面试题9:用两个栈实现队列 题目:如面试题,给你两个栈, 实现队列的先进先出,即在队列头删除一个元素以及在队列的尾部添加一个元素 思路:这个题的分析感觉很巧妙,从一个具体的例子入手,找出其中的 ...

  2. lua学习之函数篇

    函数 函数是对语句和表达式进行抽象的主要机制 两种用法 一是可以完成特定的任务,一句函数调用被视为一条语句 二是以只用来计算并返回特定的结果,视为一句表达式 print("Hello, Wo ...

  3. D语言-随机数游戏

    由于不会D语言的随机数,干脆core.stdc.stdlib调用stdlib.h 这里mark一下,类型转换是cast(D语言类型) NULL不能用,要用null import std.stdio; ...

  4. Centos7.6安装zabbix留纪录

    1)查看系统版本 [root@zabbix-s41 ~]# cat /etc/redhat-release CentOS Linux release (Core) [root@zabbix-s41 ~ ...

  5. k8s系列---EFK日志系统

    文章拷于:http://blog.itpub.net/28916011/viewspace-2216748/   用于自己备份记录错误 一个完整的k8s集群,应该包含如下六大部分:kube-dns.i ...

  6. Linux Shell 计算脚本执行过程用了多长时间

    #!/bin/bash starttime=`date +'%Y-%m-%d %H:%M:%S'` #执行程序 endtime=`date +'%Y-%m-%d %H:%M:%S'`start_sec ...

  7. MySQL全文索引、联合索引、like查询、json查询速度大比拼

    目录 查询背景 一.like查询 二.json函数查询 三.联合索引查询 四.全文索引查询 结论 查询背景 有一个表tmp_test_course大概有10万条记录,然后有个json字段叫outlin ...

  8. Linux系统WEB服务之Nginx基础入门

    一.Nginxi简介 Nginx是什么?它是一个开源.高性能的WEB服务器软件和代理服务器软件,由俄罗斯人Igor Sysoev 开发实现.它的功能主要分三类,第一是它作为一个WEB服务软件使用:第二 ...

  9. ClientAbortException :客户端异常终止

    ClientAbortException :客户端异常终止 java.io.IOException: 你的主机中的软件中止了一个已建立的连接. 罪魁祸首: <img src="chec ...

  10. go程序基于阿里云CodePipeline的一次devops实践

    背景 最近朋友有个项目代码托管用的码云,测试服务器(阿里云ECS)只有一台,三四个人开发,于是想基于阿里云的CodePipeline快速打造一套自动化cicd的流程,使用docker来进行多套环境部署 ...