前言

如题,今天介绍 springboot 通过jdbc访问关系型mysql,通过 spring 的 JdbcTemplate 去访问。

准备工作

  • SpringBoot 2.x
  • jdk 1.8
  • maven 3.0
  • idea
  • mysql

构建 SpringBoot 项目,不会的朋友参考旧文章:如何使用 IDEA 构建 Spring Boot 工程

项目目录结构

pom 文件引入依赖

<dependencies>
<!-- jdbcTemplate 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 开启web: -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- mysql连接类 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<!-- druid 连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.13</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

application.yaml 配置数据库信息

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true
username: 数据库用户名
password: 数据库密码

实体类

package com.nasus.domain;

/**
* Project Name:jdbctemplate_demo <br/>
* Package Name:com.nasus.domain <br/>
* Date:2019/2/3 10:55 <br/>
* <b>Description:</b> TODO: 描述该类的作用 <br/>
*
* @author <a href="turodog@foxmail.com">nasus</a><br/>
* Copyright Notice =========================================================
* This file contains proprietary information of Eastcom Technologies Co. Ltd.
* Copying or reproduction without prior written approval is prohibited.
* Copyright (c) 2019 =======================================================
*/
public class Student { private Integer id; private String name; private Integer age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} @Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}

dao 层

package com.nasus.dao;

import com.nasus.domain.Student;
import java.util.List; /**
* Project Name:jdbctemplate_demo <br/>
* Package Name:com.nasus.dao <br/>
* Date:2019/2/3 10:59 <br/>
* <b>Description:</b> TODO: 描述该类的作用 <br/>
* @author <a href="turodog@foxmail.com">nasus</a><br/>
*/
public interface IStudentDao { int add(Student student); int update(Student student); int delete(int id); Student findStudentById(int id); List<Student> findStudentList(); }

具体实现类:

package com.nasus.dao.impl;

import com.nasus.dao.IStudentDao;
import com.nasus.domain.Student;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository; /**
* Project Name:jdbctemplate_demo <br/>
* Package Name:com.nasus.dao.impl <br/>
* Date:2019/2/3 11:00 <br/>
* <b>Description:</b> TODO: 描述该类的作用 <br/>
*
* @author <a href="turodog@foxmail.com">nasus</a><br/>
*/
@Repository
public class IStudentDaoImpl implements IStudentDao{ @Autowired
private JdbcTemplate jdbcTemplate; @Override
public int add(Student student) {
return jdbcTemplate.update("insert into student(name, age) values(?, ?)",
student.getName(),student.getAge());
} @Override
public int update(Student student) {
return jdbcTemplate.update("UPDATE student SET NAME=? ,age=? WHERE id=?",
student.getName(),student.getAge(),student.getId());
} @Override
public int delete(int id) {
return jdbcTemplate.update("DELETE from TABLE student where id=?",id);
} @Override
public Student findStudentById(int id) {
// BeanPropertyRowMapper 使获取的 List 结果列表的数据库字段和实体类自动对应
List<Student> list = jdbcTemplate.query("select * from student where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Student.class));
if(list!=null && list.size()>0){
Student student = list.get(0);
return student;
}else{
return null;
}
} @Override
public List<Student> findStudentList() {
// 使用Spring的JdbcTemplate查询数据库,获取List结果列表,数据库表字段和实体类自动对应,可以使用BeanPropertyRowMapper
List<Student> list = jdbcTemplate.query("select * from student", new Object[]{}, new BeanPropertyRowMapper(Student.class));
if(list!=null && list.size()>0){
return list;
}else{
return null;
}
} }

service 层

package com.nasus.service;

import com.nasus.domain.Student;
import java.util.List; /**
* Project Name:jdbctemplate_demo <br/>
* Package Name:com.nasus.service <br/>
* Date:2019/2/3 11:17 <br/>
* <b>Description:</b> TODO: 描述该类的作用 <br/>
*
* @author <a href="turodog@foxmail.com">nasus</a><br/>
*/
public interface IStudentService { int add(Student student); int update(Student student); int delete(int id); Student findStudentById(int id); List<Student> findStudentList(); }

实现类:

package com.nasus.service.impl;

import com.nasus.dao.IStudentDao;
import com.nasus.domain.Student;
import com.nasus.service.IStudentService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; /**
* Project Name:jdbctemplate_demo <br/>
* Package Name:com.nasus.service.impl <br/>
* Date:2019/2/3 11:18 <br/>
* <b>Description:</b> TODO: 描述该类的作用 <br/>
*
* @author <a href="turodog@foxmail.com">nasus</a><br/>
* Copyright Notice =========================================================
* This file contains proprietary information of Eastcom Technologies Co. Ltd.
* Copying or reproduction without prior written approval is prohibited.
* Copyright (c) 2019 =======================================================
*/
@Repository
public class IStudentServiceImpl implements IStudentService { @Autowired
private IStudentDao iStudentDao; @Override
public int add(Student student) {
return iStudentDao.add(student);
} @Override
public int update(Student student) {
return iStudentDao.update(student);
} @Override
public int delete(int id) {
return iStudentDao.delete(id);
} @Override
public Student findStudentById(int id) {
return iStudentDao.findStudentById(id);
} @Override
public List<Student> findStudentList() {
return iStudentDao.findStudentList();
} }

controller 构建 restful api

package com.nasus.controller;

import com.nasus.domain.Student;
import com.nasus.service.IStudentService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
* Project Name:jdbctemplate_demo <br/>
* Package Name:com.nasus.controller <br/>
* Date:2019/2/3 11:21 <br/>
* <b>Description:</b> TODO: 描述该类的作用 <br/>
*
* @author <a href="turodog@foxmail.com">nasus</a><br/>
*/
@RestController
@RequestMapping("/student")
public class StudentController { @Autowired
private IStudentService iStudentService; @PostMapping("")
public int addStudent(@RequestBody Student student){
return iStudentService.add(student);
} @PutMapping("/{id}")
public String updateStudent(@PathVariable Integer id, @RequestBody Student student){
Student oldStudent = new Student();
oldStudent.setId(id);
oldStudent.setName(student.getName());
oldStudent.setAge(student.getAge());
int t = iStudentService.update(oldStudent);
if (t == 1){
return student.toString();
}else {
return "更新学生信息错误";
}
} @GetMapping("/{id}")
public Student findStudentById(@PathVariable Integer id){
return iStudentService.findStudentById(id);
} @GetMapping("/list")
public List<Student> findStudentList(){
return iStudentService.findStudentList();
} @DeleteMapping("/{id}")
public int deleteStudentById(@PathVariable Integer id){
return iStudentService.delete(id);
}
}

演示结果

其他的 api 测试可以通过 postman 测试。我这里已经全部测试通过,请放心使用。

源码下载:https://github.com/turoDog/Demo/tree/master/jdbctemplate_demo

后语

以上SpringBoot 用 JdbcTemplates 访问Mysql 的教程。最后,对 Python 、Java 感兴趣请长按二维码关注一波,我会努力带给你们价值,如果觉得本文对你哪怕有一丁点帮助,请帮忙点好看,让更多人知道。

如果看到这里,说明你喜欢这篇文章,请转发、点赞。微信搜索「一个优秀的废人」,关注后回复「1024」送你一套完整的 java 教程。



Spring Boot2 系列教程 (六) | 使用 JdbcTemplates 访问 Mysql的更多相关文章

  1. Spring Boot2 系列教程(六)自定义 Spring Boot 中的 starter

    我们使用 Spring Boot,基本上都是沉醉在它 Stater 的方便之中.Starter 为我们带来了众多的自动化配置,有了这些自动化配置,我们可以不费吹灰之力就能搭建一个生产级开发环境,有的小 ...

  2. Spring Boot2 系列教程(三十)Spring Boot 整合 Ehcache

    用惯了 Redis ,很多人已经忘记了还有另一个缓存方案 Ehcache ,是的,在 Redis 一统江湖的时代,Ehcache 渐渐有点没落了,不过,我们还是有必要了解下 Ehcache ,在有的场 ...

  3. Spring Boot2 系列教程(二十)Spring Boot 整合JdbcTemplate 多数据源

    多数据源配置也算是一个常见的开发需求,Spring 和 SpringBoot 中,对此都有相应的解决方案,不过一般来说,如果有多数据源的需求,我还是建议首选分布式数据库中间件 MyCat 去解决相关问 ...

  4. Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis

    在 Redis 出现之前,我们的缓存框架各种各样,有了 Redis ,缓存方案基本上都统一了,关于 Redis,松哥之前有一个系列教程,尚不了解 Redis 的小伙伴可以参考这个教程: Redis 教 ...

  5. Spring Boot2 系列教程 (七) | 使用 Spring Data JPA 访问 Mysql

    前言 如题,今天介绍 Spring Data JPA 的使用. 什么是 Spring Data JPA 在介绍 Spring Data JPA 之前,首先介绍 Hibernate . Hibernat ...

  6. Spring Boot2 系列教程(二)创建 Spring Boot 项目的三种方式

    我最早是 2016 年底开始写 Spring Boot 相关的博客,当时使用的版本还是 1.4.x ,文章发表在 CSDN 上,阅读量最大的一篇有 43W+,如下图: 2017 年由于种种原因,就没有 ...

  7. Spring Boot2 系列教程(十)Spring Boot 整合 Freemarker

    今天来聊聊 Spring Boot 整合 Freemarker. Freemarker 简介 这是一个相当老牌的开源的免费的模版引擎.通过 Freemarker 模版,我们可以将数据渲染成 HTML ...

  8. Spring Boot2 系列教程(二十八)Spring Boot 整合 Session 共享

    这篇文章是松哥的原创,但是在第一次发布的时候,忘了标记原创,结果被好多号转发,导致我后来整理的时候自己没法标记原创了.写了几百篇原创技术干货了,有一两篇忘记标记原创进而造成的一点点小小损失也能接受,不 ...

  9. Spring Boot2 系列教程 (十) | 实现声明式事务

    前言 如题,今天介绍 SpringBoot 的 声明式事务. Spring 的事务机制 所有的数据访问技术都有事务处理机制,这些技术提供了 API 用于开启事务.提交事务来完成数据操作,或者在发生错误 ...

随机推荐

  1. java 集合类 & 容器

    为什么出现集合类? 面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就要对对象进行存储,集合就是存储对象最常用的一种方式. 数组和集合类同是容器,有何不同? 数组虽然也可以存储 ...

  2. ASP.NET MVC 实现页落网资源分享网站+充值管理+后台管理(6)之配置文件设置

    现在该有的结构和层级都有了,下面我们就开始实际应用,首先把需要用的js,css,图片放到Content文件夹中. 这里不详细讲解,大家可根据自己的实际情况,使用合适自己的前端框架,也可以点击下载本项目 ...

  3. 2018.11.23 浪在ACM 集训队第六次测试赛

    2018.11.23 浪在ACM 集训队第六次测试赛 整理人:刘文胜 div 2: A: Jam的计数法 参考博客:[1] 万众 B:数列 参考博客: [1] C:摆花 参考博客: [1] D:文化之 ...

  4. 移动端开发touchstart,touchmove,touchend事件详解和项目

    移动端开发touchstart,touchmove,touchend事件详解和项目 最近在做移动端的开发,在一个“服务商管理”页面使用到了触摸事件"touchstart",&quo ...

  5. JavaSE基础知识---常用对象API之String类

    一.String类 Java中用String类对字符串进行了对象的封装,这样的好处在于对象封装后可以定义N多属性和行为,就可以对字符串这种常见的数据进行方便的操作. 格式:(1)String s1 = ...

  6. koa2入门--09.art-template高速模板引擎的使用

    首先在项目文件夹下使用 cmd,输入:npm install --save art-template koa-template art-template语法参考:http://aui.github.i ...

  7. html5中的audio和video属性和事件汇总

    <audio> 标签属性: src:音乐的URL preload:预加载 autoplay:自动播放 loop:循环播放 controls:浏览器自带的控制 <video> 标 ...

  8. Docker 安装nginx 与端口映射

    1. 拉取镜像(网易云docker镜像仓库) docker pull hub.c.163.com/library/nginx:latest 2. 运行nignx,并做端口映射 -d 后台运行  -p映 ...

  9. 浮点数NaN和INF(#IND, #INF)

    NaN&INF定义在一些情况会出现无效的浮点数,例如除0,例如负数求平方根等,像这类情况,获取到的浮点数的值是无效的. NaN 即 Not a Number         非数字 INF  ...

  10. SpringBoot中的五种对静态资源的映射规则

    目录 1.​ webjars:以jar包的方式引入静态资源 2./** 访问当前项目的任何资源 3.首页index.html,被" /** "映射 4.自定义图标 / favico ...