SpringBoot 学习笔记

    技术2022-07-16  68

    SpringBoot 学习笔记_整合持久层——JdbcTemplate

    声明:

    本次学习参考 《SpringBoot + Vue 开发实战》 · 王松(著) 一书。

    本文的目的是记录我学习的过程和遇到的一些问题以及解决办法,其内容主要来源于原书。

    如有侵权,请联系我删除

    文章目录

    SpringBoot 学习笔记_整合持久层——JdbcTemplateSpringBoot 整合持久层开发整合 JdbcTemplate

    SpringBoot 整合持久层开发

    整合 JdbcTemplate

    JdbcTemplate 是 Spring 提供的一套 JDBC 模板框架,利用 AOP 技术来解决直接使用 JDBC 时大量重复代码的问题。

    SpringBoot 对 JdbcTemplate 的使用提供了自动化配置类 JdbcTemplateAutoConfiguration

    @Configuration @ConditionalOnClass({ DataSource.class, JdbcTemplate.class }) @ConditionalOnSingleCandidate(DataSource.class) @AutoConfigureAfter(DataSourceAutoConfiguration.class) @EnableConfigurationProperties(JdbcProperties.class) public class JdbcTemplateAutoConfiguration { @Configuarion static class JdbcTemplateConfiguration { ... @Bean @Primary @ConditionalOnMissingBean(JdbcOperations.class) public JdbcTemplate jdbcTemplate(){ ... } } }

    从上源码可以看出,当 classpath 下存在 DataSource 和 JdbcTemplate 并且 DataSource 只有一个实例时,自动配置才会生效

    若开发者没有提供 JdbcOperations,则 SpringBoot 会自动向容器中注入一个 JdbcTemplate。

    创建数据库和表

    create database `chapter05` default character set utf8; use `chapter05`; create table book( `id` int(11) not null auto_increment, `name` varchar(128) default null, `author` varchar(64) default null, primary key(`id`) ) engine=Innodb default charset=utf8; insert into `book`(`id`, `name`, `author`) values (1, '三国演义', '罗贯中'), (2, '水浒传', '施耐庵'), (3, '红楼梦', '曹雪芹'), (4, '西游记', '吴承恩');

    创建 SpringBoot 项目,添加依赖

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</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>

    数据库配置(application.properties)

    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #spring.datasource.url=jdbc:mysql:///chapter05 spring.datasource.url=jdbc:mysql://localhost:3306/chapter05?serverTimezone=GMT spring.datasource.username=root spring.datasource.password=root 报错: The server time zone value ‘�й���׼ʱ��’ is unrecognized or represents more than one time zone

    原因:mySql 8 版本的时区与系统时区差异造成,需要手动指定时区,或者降低 mySql 版本至 5

    解决: 需要在连接字符串后加上 ?serverTimezone=GMT

    创建实体类

    public class Books { private Integer id; private String name; private String author; /** Getter & Setter */ }

    创建数据库访问层

    @Repository public class BooksDao { @Autowired JdbcTemplate jdbcTemplate; public int addBook(Books book){ String sql = "INSERT INTO book(name, author) VALUES(?,?)"; return jdbcTemplate.update(sql, book.getName(), book.getAuthor()); } public int updateBook(Books book){ String sql = "UPDATE book SET name=?, author=? WHERE id=?"; return jdbcTemplate.update(sql, book.getName(), book.getAuthor(), book.getId()); } public int deleteBookById(Integer id){ String sql = "DELETE FROM book WHERE id=?"; return jdbcTemplate.update(sql, id); } public Books getBookById(Integer id){ String sql = "SELECT * FROM book WHERE id=?"; return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Books.class), id); } public List<Books> getAllBooks(){ String sql = "SELECT * FROM book"; return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Books.class)); } } 创建 BookDao,注入 JdbcTemplate。由于添加了 spring-jdbc 相关依赖,JdbcTemplate 会被自动注册到 Spring 容器,因此这里可以直接注入 JdbcTemplate 使用JdbcTemplate 中,主要分三种操作:增删改(update、batchUpdate)、查询(query、queryForObject)、执行其他SQL或存储过程等(execute)查询操作时,需要一个 RowMapper 将查询出来的列和实体类的属性一一对应。如果列名和属性都是相同的,那么可以直接使用 BeanPropertyRowMapper,如果列名和属性名不同,就需要开发者自己实现 RowMapper 接口,将列和实体类属性对应。

    创建 Service 和 Controller

    @Service public class BooksService { @Autowired BooksDao booksDao; public int addBook(Books book){ return booksDao.addBook(book); } public int updateBook(Books book){ return booksDao.updateBook(book); } public int deleteBook(Integer id){ return booksDao.deleteBookById(id); } public Books getBookById(Integer id){ return booksDao.getBookById(id); } public List<Books> getAllBooks(){ return booksDao.getAllBooks(); } } @RestController public class BooksController { @Autowired BooksService booksService; @GetMapping("/bookOps") public void bookOps() { Books b1 = new Books(); b1.setId(6); b1.setName("朝花夕拾"); b1.setAuthor("鲁迅"); int i = booksService.addBook(b1); System.out.println("add Book " + i + "条 >>> " + b1.getName()); Books b2 = new Books(); b2.setId(5); b2.setName("SpringBoot 开发实战"); b2.setAuthor("王松"); int j = booksService.updateBook(b2); System.out.println("update Book" + j + "条 >>> " + b2.getName()); Books b3 = booksService.getBookById(5); System.out.println("getBookById >>> " + b3.getName()); int k = booksService.deleteBook(5); System.out.println("deleteBook" + k + "条 >>> id = " + "5"); List<Books> allBooks = booksService.getAllBooks(); System.out.println("getAllBooks >>> " + allBooks); } }

    启动项目,测试

    Processed: 0.008, SQL: 9