SpringBoot:SpringBoot整合JdbcTemplate
个人其实偏向于使用类似于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的更多相关文章
- springboot 整合jdbcTemplate
springboot 整合jdbcTemplate 〇.搭建springboot环境(包括数据库的依赖) 一.添加依赖 如果导入了jpa的依赖,就不用导入jdbctemplete的依赖了jpa的依赖: ...
- SpringBoot第四篇:整合JDBCTemplate
作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10868954.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言 前面几篇文 ...
- SpringBoot第四集:整合JdbcTemplate和JPA(2020最新最易懂)
SpringBoot第四集:整合JdbcTemplate和JPA(2020最新最易懂) 当前环境说明: Windows10_64 Maven3.x JDK1.8 MySQL5.6 SpringTool ...
- SpringBoot 同时整合thymeleaf html、vue html和jsp
问题描述 SpringBoot如何同时访问html和jsp SpringBoot访问html页面可以,访问jsp页面报错 SpringBoot如何同时整合thymeleaf html.vue html ...
- SpringBoot+AOP整合
SpringBoot+AOP整合 https://blog.csdn.net/lmb55/article/details/82470388 https://www.cnblogs.com/onlyma ...
- SpringBoot+Redis整合
SpringBoot+Redis整合 1.在pom.xml添加Redis依赖 <!--整合Redis--> <dependency> <groupId>org.sp ...
- SpringBoot+Swagger整合API
SpringBoot+Swagger整合API Swagger:整合规范的api,有界面的操作,测试 1.在pom.xml加入swagger依赖 <!--整合Swagger2配置类--> ...
- springboot+maven整合spring security
springboot+maven整合spring security已经做了两次了,然而还是不太熟悉,这里针对后台简单记录一下需要做哪些事情,具体的步骤怎么操作网上都有,不再赘述.1.pom.xml中添 ...
- springboot下整合各种配置文件
本博是在springboot下整合其他中间件,比如,mq,redis,durid,日志...等等 以后遇到再更.springboot真是太便捷了,让我们赶紧涌入到springboot的怀抱吧. ap ...
- SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版)
SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版) ================================ ©Copyright 蕃薯耀 2 ...
随机推荐
- WCF学习笔记二
客户端调用WCF服务出现以下错误: “/”应用程序中的服务器错误. 远程服务器返回错误: (415) Unsupported Media Type. 说明: 执行当前 Web 请求期间,出现未经处理的 ...
- .Net Core:Middleware自定义中间件
新建standard类库项目,添加引用包 Microsoft.AspNetCore 1.扩展IApplicationBuilder using Microsoft.AspNetCore.Builder ...
- JavsScript 一些技巧方法
直接定义一个匿名函数,并立即调用: (function(){ //TODO: }()); 说明:function之前的左圆括号是必需的,如果不写这个,JavaScript解析器会试图将关键字f ...
- Codeforces 1220 E Tourism
题面 可以发现一个边双必然是可以随意走的,所以我们就把原图求割边然后把边双缩成一个点,然后就是一个树上dp了. #include<bits/stdc++.h> #define ll lon ...
- Zabbix+Grafana 展示示例1
Zabbix+Grafana 展示示例 Grafana是一个跨平台的开源度量分析和可是化的工具,可以通过该将采集的数据查询然后可视化的展示,并及时通知. 1. Grafana 特性 1. 展示方式:快 ...
- Appium Inspector定位Webview/H5页面元素
目录 操作步骤 Python操作该混合App代码 Appium在操作混合App或Android App的H5页面时, 常常需要定位H5页面中的元素, 传统方式是 翻墙 + 使用Chrome://ins ...
- 使用Android手机作为树莓派的屏幕
在使用树莓派时,有时出于应急,身边没有屏幕,或者外出携带时也不方便带着屏幕走.如果能使用随身携带的智能手机当做其屏幕,则会方便许多.看看效果,一个树莓派+充电宝+手机,就会非常有用了. 满足以下条件即 ...
- 浏览器环境下的microtaks和macrotasks
带有可视代码执行顺序的原文链接https://jakearchibald.com/201...,此篇文字并非其完整翻译,加入了一部分自己的理解,比如将其中的task替换为macrotask或是删除了可 ...
- iOS App的几种安全防范
虽然公司的项目目前还不算健壮,安全问题对于大部分小公司来说似乎并没什么必要,不过要攻击的话,我有十足的把握,我们是无法承受冲击的.嘿嘿嘿~不过带着一颗入坑iOS的心思,搜集了一下资料后,还是做了一些尝 ...
- 深入探索REST(2):理解本真的REST架构风格
文章转载地址:https://www.infoq.cn/article/understanding-restful-style/,如引用请标注文章原地址 引子 在移动互联网.云计算迅猛发展的今天,作为 ...