本文讲解 Spring Boot 基础下,如何使用 JDBC,配置数据源和通过 JdbcTemplate 编写数据访问。

环境依赖

修改 POM 文件,添加spring-boot-starter-jdbc依赖。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-jdbc</artifactId>
  4. </dependency>

添加mysql依赖。

  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. <version>5.1.35</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>druid</artifactId>
  9. <version>1.0.14</version>
  10. </dependency>

数据源

方案一 使用 Spring Boot 默认配置

使用 Spring Boot 默认配置,不需要在创建 dataSource 和 jdbcTemplate 的 Bean。

src/main/resources/application.properties 中配置数据源信息。

  1. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  2. spring.datasource.url=jdbc:mysql://localhost:3307/springboot_db
  3. spring.datasource.username=root
  4. spring.datasource.password=root

方案二 手动创建

src/main/resources/config/source.properties 中配置数据源信息。

  1. # mysql
  2. source.driverClassName = com.mysql.jdbc.Driver
  3. source.url = jdbc:mysql://localhost:3306/springboot_db
  4. source.username = root
  5. source.password = root

通过 Java Config 创建 dataSource 和jdbcTemplate。

  1. @Configuration
  2. @EnableTransactionManagement
  3. @PropertySource(value = {"classpath:config/source.properties"})
  4. public class BeanConfig {
  5. @Autowired
  6. private Environment env;
  7. @Bean(destroyMethod = "close")
  8. public DataSource dataSource() {
  9. DruidDataSource dataSource = new DruidDataSource();
  10. dataSource.setDriverClassName(env.getProperty("source.driverClassName").trim());
  11. dataSource.setUrl(env.getProperty("source.url").trim());
  12. dataSource.setUsername(env.getProperty("source.username").trim());
  13. dataSource.setPassword(env.getProperty("source.password").trim());
  14. return dataSource;
  15. }
  16. @Bean
  17. public JdbcTemplate jdbcTemplate() {
  18. JdbcTemplate jdbcTemplate = new JdbcTemplate();
  19. jdbcTemplate.setDataSource(dataSource());
  20. return jdbcTemplate;
  21. }
  22. }

脚本初始化

先初始化需要用到的SQL脚本。

  1. CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
  2. USE `springboot_db`;
  3. DROP TABLE IF EXISTS `t_author`;
  4. CREATE TABLE `t_author` (
  5. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  6. `real_name` varchar(32) NOT NULL COMMENT '用户名称',
  7. `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

使用JdbcTemplate操作

实体对象

  1. public class Author {
  2. private Long id;
  3. private String realName;
  4. private String nickName;
  5. // SET和GET方法
  6. }

DAO相关

  1. public interface AuthorDao {
  2. int add(Author author);
  3. int update(Author author);
  4. int delete(Long id);
  5. Author findAuthor(Long id);
  6. List<Author> findAuthorList();
  7. }

我们来定义实现类,通过JdbcTemplate定义的数据访问操作。

  1. @Repository
  2. public class AuthorDaoImpl implements AuthorDao {
  3. @Autowired
  4. private JdbcTemplate jdbcTemplate;
  5. @Override
  6. public int add(Author author) {
  7. return jdbcTemplate.update("insert into t_author(real_name, nick_name) values(?, ?)",
  8. author.getRealName(), author.getNickName());
  9. }
  10. @Override
  11. public int update(Author author) {
  12. return jdbcTemplate.update("update t_author set real_name = ?, nick_name = ? where id = ?",
  13. new Object[]{author.getRealName(), author.getNickName(), author.getId()});
  14. }
  15. @Override
  16. public int delete(Long id) {
  17. return jdbcTemplate.update("delete from t_author where id = ?", id);
  18. }
  19. @Override
  20. public Author findAuthor(Long id) {
  21. List<Author> list = jdbcTemplate.query("select * from t_author where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Author.class));
  22. if(null != list && list.size()>0){
  23. Author auhtor = list.get(0);
  24. return auhtor;
  25. }else{
  26. return null;
  27. }
  28. }
  29. @Override
  30. public List<Author> findAuthorList() {
  31. List<Author> list = jdbcTemplate.query("select * from t_author", new Object[]{}, new BeanPropertyRowMapper<Author>(Author.class));
  32. return list;
  33. }
  34. }

Service相关

  1. public interface AuthorService {
  2. int add(Author author);
  3. int update(Author author);
  4. int delete(Long id);
  5. Author findAuthor(Long id);
  6. List<Author> findAuthorList();
  7. }

我们来定义实现类,Service层调用Dao层的方法,这个是典型的套路。

  1. @Service("authorService")
  2. public class AuthorServiceImpl implements AuthorService {
  3. @Autowired
  4. private AuthorDao authorDao;
  5. @Override
  6. public int add(Author author) {
  7. return this.authorDao.add(author);
  8. }
  9. @Override
  10. public int update(Author author) {
  11. return this.authorDao.update(author);
  12. }
  13. @Override
  14. public int delete(Long id) {
  15. return this.authorDao.delete(id);
  16. }
  17. @Override
  18. public Author findAuthor(Long id) {
  19. return this.authorDao.findAuthor(id);
  20. }
  21. @Override
  22. public List<Author> findAuthorList() {
  23. return this.authorDao.findAuthorList();
  24. }
  25. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController
  2. @RequestMapping(value="/data/jdbc/author")
  3. public class AuthorController {
  4. @Autowired
  5. private AuthorService authorService;
  6. /**
  7. * 查询用户列表
  8. */
  9. @RequestMapping(method = RequestMethod.GET)
  10. public Map<String,Object> getAuthorList(HttpServletRequest request) {
  11. List<Author> authorList = this.authorService.findAuthorList();
  12. Map<String,Object> param = new HashMap<String,Object>();
  13. param.put("total", authorList.size());
  14. param.put("rows", authorList);
  15. return param;
  16. }
  17. /**
  18. * 查询用户信息
  19. */
  20. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  21. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  22. Author author = this.authorService.findAuthor(userId);
  23. if(author == null){
  24. throw new RuntimeException("查询错误");
  25. }
  26. return author;
  27. }
  28. /**
  29. * 新增方法
  30. */
  31. @RequestMapping(method = RequestMethod.POST)
  32. public void add(@RequestBody JSONObject jsonObject) {
  33. String userId = jsonObject.getString("user_id");
  34. String realName = jsonObject.getString("real_name");
  35. String nickName = jsonObject.getString("nick_name");
  36. Author author = new Author();
  37. if (author!=null) {
  38. author.setId(Long.valueOf(userId));
  39. }
  40. author.setRealName(realName);
  41. author.setNickName(nickName);
  42. try{
  43. this.authorService.add(author);
  44. }catch(Exception e){
  45. e.printStackTrace();
  46. throw new RuntimeException("新增错误");
  47. }
  48. }
  49. /**
  50. * 更新方法
  51. */
  52. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
  53. public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
  54. Author author = this.authorService.findAuthor(userId);
  55. String realName = jsonObject.getString("real_name");
  56. String nickName = jsonObject.getString("nick_name");
  57. author.setRealName(realName);
  58. author.setNickName(nickName);
  59. try{
  60. this.authorService.update(author);
  61. }catch(Exception e){
  62. e.printStackTrace();
  63. throw new RuntimeException("更新错误");
  64. }
  65. }
  66. /**
  67. * 删除方法
  68. */
  69. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
  70. public void delete(@PathVariable Long userId) {
  71. try{
  72. this.authorService.delete(userId);
  73. }catch(Exception e){
  74. throw new RuntimeException("删除错误");
  75. }
  76. }
  77. }

总结

通过,上面这个简单的案例,我们发现 Spring Boot 仍然秉承了 Spring 框架的一贯套路,并简化 Spring 应用的初始搭建以及开发过程。

springboot---数据整合篇的更多相关文章

  1. Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合

    文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...

  2. Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合

    文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. MyBatis整合5. 总结 4.1. 方案一 通过 ...

  3. SpringBoot第六篇:整合通用Mapper

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10876339.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言   在以往的项 ...

  4. 大数据工具篇之Hive与MySQL整合完整教程

    大数据工具篇之Hive与MySQL整合完整教程 一.引言 Hive元数据存储可以放到RDBMS数据库中,本文以Hive与MySQL数据库的整合为目标,详细说明Hive与MySQL的整合方法. 二.安装 ...

  5. 大数据工具篇之Hive与HBase整合完整教程

    大数据工具篇之Hive与HBase整合完整教程 一.引言 最近的一次培训,用户特意提到Hadoop环境下HDFS中存储的文件如何才能导入到HBase,关于这部分基于HBase Java API的写入方 ...

  6. SpringBoot第七篇:整合Mybatis-Plus

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10881666.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言   一看这个名 ...

  7. SpringBoot数据访问之整合mybatis注解版

    SpringBoot数据访问之整合mybatis注解版 mybatis注解版: 贴心链接:Github 在网页下方,找到快速开始文档 上述链接方便读者查找. 通过快速开始文档,搭建环境: 创建数据库: ...

  8. 使用VUE+SpringBoot+EasyExcel 整合导入导出数据

    使用VUE+SpringBoot+EasyExcel 整合导入导出数据 创建一个普通的maven项目即可 项目目录结构 1 前端 存放在resources/static 下 index.html &l ...

  9. thymeleaf第二篇:理解原理并为后面springboot进行整合进行铺垫

    官方入门之从虚拟商店理解thymeleaf 参考文档: 简单使用Thymeleaf API渲染模板生成静态页面 邮件通知改造之Thymeleaf渲染模板生成静态页面--看懂会帮助理解springboo ...

  10. Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch

    文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...

随机推荐

  1. mac终端显示日历信息命令

    cal 命令: 用法: usage: cal [-jy] [[month] year] cal [-j] [-m month] [year] ncal [-Jjpwy] [-s country_cod ...

  2. ZOJ2588:Burning Bridges(无向连通图求割边)

    题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1588 吐下槽,不得不说ZOJ好坑,模版题做了一个多小时. 题意:*    ...

  3. sdut AOE网上的关键路径(spfa+前向星)

    http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2498&cid=1304 题目描述 一个无环的有向图称为无环图(Directed Acyc ...

  4. Selenium IDE脚本录制步骤简介

    录制脚本步骤: 1.打开Selenium IDE,输入需要录制脚本的地址,然后启动Firefox,输入selenium IDE需录制的地址,根据实际需求,做相关操作: 2.录制过程中,会发现做的相关操 ...

  5. python开发之路目录

    Python 目录 基础 python入门 python数据类型.字符编码.文件处理 python函数基础 python函数进阶 python装饰器函数 python装饰器函数 python递归函数 ...

  6. 企业级服务元年:iClap高效解决手游更新迭代问题

    2006年至今,手游市场经历了不少变革,从WAP站到2009年智能手机时代来临,2012大量资本涌入国内手游行业,到2014年手游市场趋于成熟,细分市场成为追逐热门,在2015年优胜劣汰的资本寒冬浪潮 ...

  7. Python: 大型数组运算

    需要在大数据集(比如数组或网格) 上面执行计算,涉及到数组的重量级运算操作,可以使用NumPy 库. 下面是一个简单的小例子,展示标准列表对象和NumPy 数组对象之间的差别 >>> ...

  8. QML事件处理 八

    1.MouseArea MouseArea 是一个不可见的项目,通常用来和一个可见的项目配合使用来为其提供鼠标处理.鼠标处理的逻辑可以包含在一个MouseArea项目中. MouseArea的enab ...

  9. python 字典(dict)get方法应用

    如果我们需要获取字典值的话,我们有两种方法,一个是通过dict['key'],另外一个就是dict.get()方法. 今天给大家分享的就是字典的get()方法. 这里我们可以用字典做一个小游戏,假设用 ...

  10. 20155201 2016-2017-2 《Java程序设计》第一周学习总结

    20155201 2016-2017-2 <Java程序设计>第一周学习总结 教材学习内容总结 每一章的问题: 第一章 Java ME都有哪些成功的平台? 第二章 哪些情况可以使用impo ...