个人其实偏向于使用类似于JdbcTemplate这种的框架,返回数据也习惯于接受Map/List形式,而不是转化成对象,一是前后台分离转成json方便,另外是返回数据格式,数据字段可以通过SQL控制,而不是返回整个对象字段数据,或者通过VO方式。当然更多人习惯于采用Bean形式,所以这里也同样使用Bean.

一、数据准备

CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`username` varchar(50) NOT NULL COMMENT '用户名',
`age` int(11) NOT NULL COMMENT '年龄',
`ctm` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('张三', '18', NOW()) ;
INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('李四', '20', NOW()) ;
INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('王五', '19', NOW()) ;

二、引入依赖

<!-- jdbcTemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <!-- MySQL连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

另外web依赖也需要,因为我们采用MVC模式。

<!-- Add typical dependencies for a web application -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

三、数据库配置文件

一如既往,我们采用yaml文件配置,当然properties文件也是一样。

注意点,SpringBoot默认采用tomcat-jdbc连接池,如果需要C3P0,DBCP,Druid等作为连接池,需要加入相关依赖以及配置,这里不作说明,采用默认配置即可。

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_user
username: root
password: root

四、代码

项目结构如下:

实体类User.class

package cn.saytime.bean;

import java.util.Date;

/**
* @ClassName cn.saytime.bean.User
* @Description
* @date 2017-07-04 22:47:28
*/
public class User { private int id;
private String username;
private int age;
private Date ctm; public User() {
} public User(String username, int age) {
this.username = username;
this.age = age;
this.ctm = new Date();
} // Getter、Setter
}

UserDao.class

package cn.saytime.dao;

import cn.saytime.bean.User;

import java.util.List;

/**
* @ClassName cn.saytime.dao.UserDao
* @Description
* @date 2017-07-04 22:48:45
*/
public interface UserDao { User getUserById(Integer id); public List<User> getUserList(); public int add(User user); public int update(Integer id, User user); public int delete(Integer id);
}

UserDaoImpl.class

package cn.saytime.dao.impl;

import cn.saytime.bean.User;
import cn.saytime.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository; import java.util.Date;
import java.util.List; /**
* @ClassName cn.saytime.dao.impl.UserDaoImpl
* @Description
* @date 2017-07-04 22:50:07
*/
@Repository
public class UserDaoImpl implements UserDao { @Autowired
private JdbcTemplate jdbcTemplate; @Override
public User getUserById(Integer id) {
List<User> list = jdbcTemplate.query("select * from tb_user where id = ?", new Object[]{id}, new BeanPropertyRowMapper(User.class));
if(list!=null && list.size()>0){
return list.get(0);
}else{
return null;
}
} @Override
public List<User> getUserList() {
List<User> list = jdbcTemplate.query("select * from tb_user", new Object[]{}, new BeanPropertyRowMapper(User.class));
if(list!=null && list.size()>0){
return list;
}else{
return null;
}
} @Override
public int add(User user) {
return jdbcTemplate.update("insert into tb_user(username, age, ctm) values(?, ?, ?)",
user.getUsername(),user.getAge(), new Date()); } @Override
public int update(Integer id, User user) {
return jdbcTemplate.update("UPDATE tb_user SET username = ? , age = ? WHERE id=?",
user.getUsername(),user.getAge(), id);
} @Override
public int delete(Integer id) {
return jdbcTemplate.update("DELETE from tb_user where id = ? ",id);
} }

UserService.class

package cn.saytime.service;

import cn.saytime.bean.User;
import org.springframework.stereotype.Service; import java.util.List; /**
* @ClassName cn.saytime.service.UserService
* @Description
* @date 2017-07-04 22:49:05
*/
public interface UserService { User getUserById(Integer id); public List<User> getUserList(); public int add(User user); public int update(Integer id, User user); public int delete(Integer id);
}

UserServiceimpl.class

package cn.saytime.service.impl;

import cn.saytime.bean.User;
import cn.saytime.dao.UserDao;
import cn.saytime.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* @ClassName cn.saytime.service.impl.UserServiceImpl
* @Description
* @date 2017-07-04 22:49:27
*/
@Service
public class UserServiceImpl implements UserService { @Autowired
private UserDao userDao; @Override
public User getUserById(Integer id) {
return userDao.getUserById(id);
} @Override
public List<User> getUserList() {
return userDao.getUserList();
} @Override
public int add(User user) {
return userDao.add(user);
} @Override
public int update(Integer id, User user) {
return userDao.update(id, user);
} @Override
public int delete(Integer id) {
return userDao.delete(id);
}
}

JsonResult.class 通用json返回类

package cn.saytime.bean;

public class JsonResult {

private String status = null;

private Object result = null;

public JsonResult status(String status) {
this.status = status;
return this;
} // Getter Setter
}

UserController.class(Restful风格)

package cn.saytime.web;

import cn.saytime.bean.JsonResult;
import cn.saytime.bean.User;
import cn.saytime.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import java.util.List; /**
* @ClassName cn.saytime.web.UserController
* @Description
* @date 2017-07-04 22:46:14
*/
@RestController
public class UserController { @Autowired
private UserService userService; /**
* 根据ID查询用户
* @param id
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
JsonResult r = new JsonResult();
try {
User user = userService.getUserById(id);
r.setResult(user);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
} /**
* 查询用户列表
* @return
*/
@RequestMapping(value = "users", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserList (){
JsonResult r = new JsonResult();
try {
List<User> users = userService.getUserList();
r.setResult(users);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
} /**
* 添加用户
* @param user
* @return
*/
@RequestMapping(value = "user", method = RequestMethod.POST)
public ResponseEntity<JsonResult> add (@RequestBody User user){
JsonResult r = new JsonResult();
try {
int orderId = userService.add(user);
if (orderId < 0) {
r.setResult(orderId);
r.setStatus("fail");
} else {
r.setResult(orderId);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error"); e.printStackTrace();
}
return ResponseEntity.ok(r);
} /**
* 根据id删除用户
* @param id
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){
JsonResult r = new JsonResult();
try {
int ret = userService.delete(id);
if (ret < 0) {
r.setResult(ret);
r.setStatus("fail");
} else {
r.setResult(ret);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error"); e.printStackTrace();
}
return ResponseEntity.ok(r);
} /**
* 根据id修改用户信息
* @param user
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){
JsonResult r = new JsonResult();
try {
int ret = userService.update(id, user);
if (ret < 0) {
r.setResult(ret);
r.setStatus("fail");
} else {
r.setResult(ret);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error"); e.printStackTrace();
}
return ResponseEntity.ok(r);
} }

五、测试
GET http://localhost:8080/users 获取用户列表

GET http://localhost:8080/user/{id} 根据ID获取用户信息

POST http://localhost:8080/user 添加用户(注意提交格式以及内容)

PUT http://localhost:8080/user/{id} 根据ID修改用户信息

再次查询所有用户信息

DELETE http://localhost:8080/user/{id} 根据ID删除用户

最终用户数据

测试结果通过,ok

demo源码地址:https://github.com/Hyiran/spJdbeTmp.git

转https://blog.csdn.net/saytime/article/details/74783294

SpringBoot:SpringBoot整合JdbcTemplate的更多相关文章

  1. springboot 整合jdbcTemplate

    springboot 整合jdbcTemplate 〇.搭建springboot环境(包括数据库的依赖) 一.添加依赖 如果导入了jpa的依赖,就不用导入jdbctemplete的依赖了jpa的依赖: ...

  2. SpringBoot第四篇:整合JDBCTemplate

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10868954.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言   前面几篇文 ...

  3. SpringBoot第四集:整合JdbcTemplate和JPA(2020最新最易懂)

    SpringBoot第四集:整合JdbcTemplate和JPA(2020最新最易懂) 当前环境说明: Windows10_64 Maven3.x JDK1.8 MySQL5.6 SpringTool ...

  4. SpringBoot 同时整合thymeleaf html、vue html和jsp

    问题描述 SpringBoot如何同时访问html和jsp SpringBoot访问html页面可以,访问jsp页面报错 SpringBoot如何同时整合thymeleaf html.vue html ...

  5. SpringBoot+AOP整合

    SpringBoot+AOP整合 https://blog.csdn.net/lmb55/article/details/82470388 https://www.cnblogs.com/onlyma ...

  6. SpringBoot+Redis整合

    SpringBoot+Redis整合 1.在pom.xml添加Redis依赖 <!--整合Redis--> <dependency> <groupId>org.sp ...

  7. SpringBoot+Swagger整合API

    SpringBoot+Swagger整合API Swagger:整合规范的api,有界面的操作,测试 1.在pom.xml加入swagger依赖 <!--整合Swagger2配置类--> ...

  8. springboot+maven整合spring security

    springboot+maven整合spring security已经做了两次了,然而还是不太熟悉,这里针对后台简单记录一下需要做哪些事情,具体的步骤怎么操作网上都有,不再赘述.1.pom.xml中添 ...

  9. springboot下整合各种配置文件

    本博是在springboot下整合其他中间件,比如,mq,redis,durid,日志...等等  以后遇到再更.springboot真是太便捷了,让我们赶紧涌入到springboot的怀抱吧. ap ...

  10. SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版)

    SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版) ================================ ©Copyright 蕃薯耀 2 ...

随机推荐

  1. 2019ICPC区域赛(银川)总结

    2019ICPC银川 作为第一次打区域赛的我,心情异常激动,加上学校给坐飞机(事实上赶飞机很痛苦). 热身赛很难受,oj上不去,写AC自动机输入没写好.. 现场赛,开场直觉倒着看,发现签到.然后看B, ...

  2. Codeforces Round #470 (rated, Div. 1, based on VK Cup 2018 Round 1) 923D 947D 948E D. Picking Strings

    题: OvO http://codeforces.com/contest/947/problem/D 923D 947D 948E 解: 记要改变的串为 P1 ,记目标串为 P2  由变化规则可得: ...

  3. 003_linuxC++之_namespace使用

    (一)引入namespace原因: 假如有很多跟人共同完成一项工程,工程中难免会有函数定义一样的名称,不可能一个一个的询问这个函数 你定义过了没有,所以引入namespace #include < ...

  4. CF796D Police Stations BFS+染色

    题意:给定一棵树,树上有一些点是警察局,要求所有点到最近的警察局的距离不大于 $d$,求最多能删几条边 ? 题解: 考虑什么时候一条边可以被断开:这条边的两个端点被两个不同的警察局覆盖掉. 我们要设计 ...

  5. 【线性代数】5-1:行列式性质(The Properties of Determinants)

    title: [线性代数]5-1:行列式性质(The Properties of Determinants) categories: Mathematic Linear Algebra keyword ...

  6. 存在日期类型的JSON数据,进行SpringMVC参数绑定时存在的问题和解决方案

    这篇文章已经过时了. 请参考比较合适的前后端交互方式. 首先是发送AJAX请求的html页面 <!DOCTYPE html> <html> <head> <m ...

  7. Linux设备驱动 之 中断处理程序

    注册中断处理程序 中断处理程序是管理硬件驱动程序的组成部分:如果设备使用中断,那么相应的驱动程序就注册一个中断处理程序: 驱动程序通过request_irq()函数注册,并且激活给定的中断线,以处理中 ...

  8. lareval重命名created_at和updated_at字段

    lareval重命名created_at和updated_at字段 一.总结 一句话总结: 要改变created_at和updated_at的名称,模型和数据迁移里面都需要改变 在模型中指定数据类型之 ...

  9. arcgis python获得别名

    import arcpy # Create a Describe object from the GDB table. # desc = arcpy.Describe(r"C:\Users\ ...

  10. ArcGIS超级工具SPTOOLS-线封闭,点集转面

    一.线封闭 操作视频:https://weibo.com/tv/v/HvyvbAxKh?fid=1034:4375207666991674 将末端不闭合线,自动生成闭合的线,效果如下 原始线:末端不闭 ...