第一章:概念

  • 为了在特定领域帮助我们简化代码,Spring 封装了很多 『Template』形式的模板类。例如:JDBCTemplate 、RedisTemplate 、RestTemplate 等等。

第二章:准备工作

2.1 环境搭建

  • IDEA 2021+。
  • JDK 11+。
  • MySQL 5.7。

2.2 导入依赖

  • pom.xml
  1. <!-- Spring -->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.3.12</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-aspects</artifactId>
  10. <version>5.3.12</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework</groupId>
  14. <artifactId>spring-test</artifactId>
  15. <version>5.3.12</version>
  16. </dependency>
  17. <!-- Spring 持久化层支持jar包 -->
  18. <!-- Spring 在执行持久化层操作、与持久化层技术进行整合过程中,需要使用orm、jdbc、tx三个jar包 -->
  19. <!-- 导入 orm 包就可以通过 Maven 的依赖传递性把其他两个也导入 -->
  20. <dependency>
  21. <groupId>org.springframework</groupId>
  22. <artifactId>spring-orm</artifactId>
  23. <version>5.3.12</version>
  24. </dependency>
  25. <!-- MySQL驱动 -->
  26. <dependency>
  27. <groupId>mysql</groupId>
  28. <artifactId>mysql-connector-java</artifactId>
  29. <version>8.0.19</version>
  30. </dependency>
  31. <!-- junit单元测试 -->
  32. <dependency>
  33. <groupId>junit</groupId>
  34. <artifactId>junit</artifactId>
  35. <version>4.13.2</version>
  36. <scope>test</scope>
  37. </dependency>
  38. <!-- 数据库连接池 -->
  39. <dependency>
  40. <groupId>com.alibaba</groupId>
  41. <artifactId>druid</artifactId>
  42. <version>1.2.8</version>
  43. </dependency>

2.3 sql 语句

  1. CREATE DATABASE IF NOT EXISTS `test` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
  2. DROP TABLE IF EXISTS `book`;
  3. CREATE TABLE `book` (
  4. `id` bigint(11) NOT NULL AUTO_INCREMENT,
  5. `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  6. `price` double NULL DEFAULT NULL,
  7. PRIMARY KEY (`id`) USING BTREE
  8. ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

2.4 数据库配置信息

  • db.properties
  1. jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
  2. jdbc.driverClass=com.mysql.cj.jdbc.Driver
  3. jdbc.username=root
  4. jdbc.password=123456

2.5 Spring 的配置文件

  • applicationContext.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns="http://www.springframework.org/schema/beans"
  6. 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 http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
  7. <!-- 配置自动扫描的包 -->
  8. <context:component-scan base-package="com.github.fairy.era"></context:component-scan>
  9. <!-- 导入数据库连接信息 -->
  10. <context:property-placeholder location="db.properties"></context:property-placeholder>
  11. <!-- 配置数据库连接池 -->
  12. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
  13. <property name="driverClassName" value="${jdbc.driverClass}"></property>
  14. <property name="url" value="${jdbc.url}"></property>
  15. <property name="username" value="${jdbc.username}"></property>
  16. <property name="password" value="${jdbc.password}"></property>
  17. </bean>
  18. <!-- 配置jdbcTemplate -->
  19. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  20. <property name="dataSource" ref="dataSource"></property>
  21. </bean>
  22. <!-- 开启AOP的注解支持 -->
  23. <aop:aspectj-autoproxy/>
  24. </beans>

2.6 测试装配的 JdbcTemplate

  • SpringTest.java
  1. package com.github.fairy.era.bean;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6. import org.springframework.test.context.ContextConfiguration;
  7. import org.springframework.test.context.junit4.SpringRunner;
  8. import javax.sql.DataSource;
  9. /**
  10. * @author 许大仙
  11. * @version 1.0
  12. * @since 2021-11-05 11:02
  13. */
  14. @RunWith(SpringRunner.class)
  15. @ContextConfiguration(value = {"classpath:applicationContext.xml"})
  16. public class SpringTest {
  17. @Autowired
  18. private DataSource dataSource;
  19. @Autowired
  20. private JdbcTemplate jdbcTemplate;
  21. @Test
  22. public void testDataSource() {
  23. System.out.println("dataSource = " + dataSource);
  24. }
  25. @Test
  26. public void testJdbcTemplate() {
  27. System.out.println("jdbcTemplate = " + jdbcTemplate);
  28. }
  29. }

第三章:JdbcTemplate 的基本用法

3.1 Dao 层接口

  • BookDao.java
  1. package com.github.fairy.era.dao;
  2. import com.github.fairy.era.bean.Book;
  3. /**
  4. * @author 许大仙
  5. * @version 1.0
  6. * @since 2021-11-09 10:42
  7. */
  8. public interface BookDao {
  9. /**
  10. * 新增
  11. *
  12. * @param book
  13. */
  14. void addBook(Book book);
  15. /**
  16. * 修改
  17. *
  18. * @param book
  19. */
  20. void updateBook(Book book);
  21. /**
  22. * 删除
  23. *
  24. * @param id
  25. */
  26. void deleteBook(Long id);
  27. /**
  28. * 查询个数
  29. */
  30. Long count();
  31. /**
  32. * 查看单个简单类型
  33. *
  34. * @param id 主键
  35. * @return 名称
  36. */
  37. String findNameById(Long id);
  38. /**
  39. * 查询实体类型
  40. *
  41. * @param id
  42. * @return
  43. */
  44. Book findById(Long id);
  45. }

3.2 Dao 层实现类

  • BookDaoImpl.java
  1. package com.github.fairy.era.dao.impl;
  2. import com.github.fairy.era.bean.Book;
  3. import com.github.fairy.era.dao.BookDao;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import org.springframework.stereotype.Repository;
  8. /**
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2021-11-09 10:43
  12. */
  13. @Repository
  14. public class BookDaoImpl implements BookDao {
  15. @Autowired
  16. private JdbcTemplate jdbcTemplate;
  17. @Override
  18. public void addBook(Book book) {
  19. jdbcTemplate.update(" INSERT INTO book (name,price) VALUES (?,?) ", book.getName(), book.getPrice());
  20. }
  21. @Override
  22. public void updateBook(Book book) {
  23. jdbcTemplate.update(" UPDATE book SET name =?,price =? WHERE id = ? ", book.getName(), book.getPrice(), book.getId());
  24. }
  25. @Override
  26. public void deleteBook(Long id) {
  27. jdbcTemplate.update(" DELETE FROM book WHERE id = ? ", id);
  28. }
  29. @Override
  30. public Long count() {
  31. return jdbcTemplate.queryForObject(" SELECT count(*) FROM book ", Long.class);
  32. }
  33. @Override
  34. public String findNameById(Long id) {
  35. return jdbcTemplate.queryForObject(" SELECT name FROM book WHERE id = ? ", String.class, id);
  36. }
  37. @Override
  38. public Book findById(Long id) {
  39. return jdbcTemplate.queryForObject(" SELECT * FROM book where id = ? ", new BeanPropertyRowMapper<>(Book.class), id);
  40. }
  41. }

3.3 测试

  1. package com.github.fairy.era.bean;
  2. import com.github.fairy.era.dao.BookDao;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.test.context.ContextConfiguration;
  7. import org.springframework.test.context.junit4.SpringRunner;
  8. /**
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2021-11-05 11:02
  12. */
  13. @RunWith(SpringRunner.class)
  14. @ContextConfiguration(value = {"classpath:applicationContext.xml"})
  15. public class SpringTest {
  16. @Autowired
  17. private BookDao bookDao;
  18. @Test
  19. public void testAddBook() {
  20. Book book = new Book(null, "《小人鱼》", 1.12);
  21. Book book2 = new Book(null, "《丑小鸭》", 2.12);
  22. Book book3 = new Book(null, "《卖火柴的小女孩》", 3.12);
  23. Book book4 = new Book(null, "《拇指姑娘》", 4.12);
  24. bookDao.addBook(book);
  25. bookDao.addBook(book2);
  26. bookDao.addBook(book3);
  27. bookDao.addBook(book4);
  28. }
  29. @Test
  30. public void testUpdateBook() {
  31. Book book = new Book(1L, "《小人鱼》", 1.13);
  32. bookDao.updateBook(book);
  33. }
  34. @Test
  35. public void testDeleteBook() {
  36. bookDao.deleteBook(1L);
  37. }
  38. @Test
  39. public void testCount() {
  40. Long count = bookDao.count();
  41. System.out.println("count = " + count);
  42. }
  43. @Test
  44. public void testFindNameById() {
  45. String name = bookDao.findNameById(1L);
  46. System.out.println("name = " + name);
  47. }
  48. @Test
  49. public void testFindById() {
  50. Book book = bookDao.findById(1L);
  51. System.out.println("book = " + book);
  52. }
  53. }