简单入门了spring boot后,接下来写写跟数据库打交道的案例。博文采用spring的jdbcTemplate工具类与数据库打交道。

下面是搭建的springbootJDBC的项目的总体架构图:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion> <groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.-SNAPSHOT</version>
<packaging>jar</packaging> <name>demo</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
</dependencies> <!--spring boot maven插件-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

接下来,贴出application.properties,设置tomcat端口号,数据库链接相关信息:

可以参照上一篇博文,参考参考如何建立一个spring boot项目,至于在选择依赖的配置时候,可以参考我下面贴出的pom.xml:

###### 设置tomcat访问端口号 ######
server.port= ###### 设置数据源 ######
spring.datasource.url=jdbc:mysql://localhost:3306/db_springboot?autoReconnect=true&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.driverClassName = com.mysql.jdbc.Driver

建立数据库tb_springboot,然后执行下面的sql脚本,生成users表:

/*
Navicat MySQL Data Transfer Source Server : localhost
Source Server Version : 50625
Source Host : localhost:3306
Source Database : db_springboot Target Server Type : MYSQL
Target Server Version : 50625
File Encoding : 65001 Date: 2017-03-31 15:01:08
*/ SET FOREIGN_KEY_CHECKS=; -- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int() NOT NULL AUTO_INCREMENT,
`name` varchar() DEFAULT NULL,
`email` varchar() DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('', 'linsen', 'linsen@126.com');
INSERT INTO `users` VALUES ('', 'sam', 'sam@qq.com');
INSERT INTO `users` VALUES ('', 'debug', 'debug@sina.com');
INSERT INTO `users` VALUES ('', '杰克', '杰克@sina.com');
INSERT INTO `users` VALUES ('', '张三', '张三@sina.com');
INSERT INTO `users` VALUES ('', '李四', '李四@sina.com');
INSERT INTO `users` VALUES ('', '王五', '王五@sina.com');
INSERT INTO `users` VALUES ('', '王五2', '王五2@sina.com');

本博文我们对spring boot与jdbcTemplate进行整合,主要当然是实现基本的 增删改查 user实体 操作,首先是开发dao层:

package com.example.repository;  

import com.example.entity.User;
import com.example.exception.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; /**
* Created by steadyjack on 2017/3/22.
* 充当dao层UserRepository
*/
@Repository
public class UserRepository { @Autowired
private JdbcTemplate jdbcTemplate; /**
* 获取用户列表
* @return
* @throws Exception
*/
@Transactional(readOnly = true)
public List<User> getUserList() throws Exception{
List<User> userList=jdbcTemplate.query("select id,name,email from users",new UserRowMapper());
System.out.println(userList);
return userList;
} /**
* 根据用户id获取用户
* @param id
* @return
* @throws Exception
*/
@Transactional(readOnly = true)
public User getUserById(Integer id) throws Exception{
//queryForObject:找不到会报异常 query:找不到则Null
//User user=jdbcTemplate.queryForObject("select id,name,email from users where id=?",new Object[]{id},new UserRowMapper());
List<User> userList=jdbcTemplate.query("select id,name,email from users where id=?",new Object[]{id},new UserRowMapper());
User user=null;
if (!userList.isEmpty()){
user=userList.get();
}
System.out.println(user);
return user;
} /**
* 插入用户数据
* @param user
* @return
* @throws Exception
*/
public int saveUser(final User user) throws Exception{
int resRow=jdbcTemplate.update("INSERT INTO users(id,name,email) VALUES(NULL,?,?)",new Object[]{
user.getName(),user.getEmail()
});
System.out.println("操作结果记录数: "+resRow);
return resRow;
} /**
* 插入用户数据-防止sql注入
* @param user
* @return
* @throws Exception
*/
public int saveUserWithSafe(final User user) throws Exception{
int resRow=jdbcTemplate.update("INSERT INTO users(id,name,email) VALUES(NULL,?,?)", new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(,user.getName());
ps.setString(,user.getEmail());
}
});
System.out.println("操作结果记录数: "+resRow);
return resRow;
} /**
* 插入用户数据-防止sql注入-可以返回该条记录的主键(注意需要指定主键)
* @param user
* @return
* @throws Exception
*/
@Transactional(rollbackFor=UserException.class)
public int saveUserWithKey(final User user) throws Exception{
String sql="INSERT INTO users(id,name,email) VALUES(NULL,?,?)";
KeyHolder keyHolder=new GeneratedKeyHolder();
int resRow=jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
PreparedStatement ps=conn.prepareStatement(sql,new String[]{"id"}); //指定 id 为主键
ps.setString(,user.getName());
ps.setString(,user.getEmail());
return ps;
}
},keyHolder);
System.out.println("操作结果记录数: "+resRow+" 主键: "+keyHolder.getKey());
return Integer.parseInt(keyHolder.getKey().toString());
} /**
* 更新用户信息
* @param user
* @return
*/
public int updateUser(final User user) throws Exception{
String sql="update users set name=?,email=? where id=?";
int resRow=jdbcTemplate.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setString(,user.getName());
preparedStatement.setString(,user.getEmail());
preparedStatement.setInt(,user.getId());
}
});
System.out.println("操作结果记录数: "+resRow);
return resRow;
} /**
* 删除用户
* @param user
* @return
* @throws Exception
*/
public int deleteUser(final User user) throws Exception{
int resRow=jdbcTemplate.update("DELETE FROM users WHERE id=?", new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(,user.getId());
}
});
System.out.println("操作结果记录数: "+resRow);
return resRow;
} /**
* 根据用户名查找用户-用于判断用户是否存在
* @param user
* @return
* @throws Exception
*/
public User getUserByUserName(final User user) throws Exception{
String sql="select id,name,email from users where name=?";
List<User> queryList=jdbcTemplate.query(sql,new UserRowMapper(),new Object[]{user.getName()});
if (queryList!=null && queryList.size()>){
return queryList.get();
}else{
return null;
}
} /**
* 获取记录数
* @return
* @throws Exception
*/
public Integer getCount() throws Exception{
String sql="select count(id) from users";
//jdbcTemplate.getMaxRows();
Integer total=jdbcTemplate.queryForObject(sql,Integer.class);
System.out.println("操作结果记录数: "+total);
return total;
} //其他的像模糊查询之类的可以自己尝试查查 jdbcTemplate 的使用文档 } /**
* 行映射
*/
class UserRowMapper implements RowMapper<User>{ @Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user=new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
return user;
} }

代码以及相关的注释我已经写在里面了,个人觉得很清晰了,如果有啥问题,可以下面留言,或者后面提到的技术交流群交流。

接下来,当然是开发controller层,在这里,我主要开发rest服务接口,结果将以json的格式返回给发起请求的客户端(以postman进行模拟),下面是我的restController:

package com.example.controller;  

import com.example.DemoApplication;
import com.example.entity.User;
import com.example.repository.UserRepository;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
import java.util.List; /**
* Created by steadyjack on 2017/3/22.
*/
@SpringBootTest(classes = DemoApplication.class)
@RestController
@RequestMapping("/user")
public class UserController { @Autowired
private UserRepository userRepository; /**
* 用户列表
* @return
*/
@RequestMapping("/list")
public List<User> listUser() {
List<User> userList=null;
try {
userList=userRepository.getUserList();
}catch (Exception e){
System.out.println("异常信息: "+e.getMessage());
}
return userList;
} /**
* 根据id查询User实体
* @param id
* @return
*/
@RequestMapping("/{id}")
public User getUserById(@PathVariable Integer id){
User user=null;
try {
user=userRepository.getUserById(id);
}catch (Exception e){
user=new User(,"admin","admin@sina.com");
System.out.println("异常信息: "+e.getMessage());
}
return user;
} /**
* 保存user实体
* @param user
* @return
*/
@RequestMapping(value = "/save",method = RequestMethod.POST)
public int insertUser(User user){
int res=;
try {
res=userRepository.saveUser(user);
}catch (Exception e){
System.out.println("异常信息: "+e.getMessage());
}
return res;
} /**
* 保存User实体-PreparedStatementSetter
* @param user
* @return
*/
@RequestMapping(value = "/saveWithSafe",method = RequestMethod.POST)
public int insertUserWithSafe(User user){
int res=;
try {
res=userRepository.saveUserWithSafe(user);
}catch (Exception e){
System.out.println("异常信息: "+e.getMessage());
}
return res;
} /**
* 保存user实体-PreparedStatementCreator、KeyHolder-保存实体后返回实体的主键
* @param user
* @return
*/
@RequestMapping(value = "/saveWithKey",method = RequestMethod.POST)
public int insertUserWithKey(User user){
int res=;
try {
res=userRepository.saveUserWithKey(user);
}catch (Exception e){
System.out.println("异常信息: "+e.getMessage());
}
return res;
} /**
* 根据id更新user实体
* @param id
* @param request
* @return
*/
@RequestMapping(value = "/update/{id}",method = RequestMethod.POST)
public int updateUserWithId(@PathVariable Integer id,HttpServletRequest request){
int res=;
try {
if (id!=null && !id.equals()){
String name=request.getParameter("name");
String email=request.getParameter("email");
User updateUser=new User(id, Strings.isNullOrEmpty(name)?null:name,Strings.isNullOrEmpty(email)?null:email);
res=userRepository.updateUser(updateUser);
}
}catch (Exception e){
System.out.println("异常信息: "+e.getMessage());
}
return res;
} /**
* 根据id删除user实体
* @param id
* @return
*/
@RequestMapping("/delete/{id}")
public int deleteUserById(@PathVariable Integer id){
int res=;
try {
User deleteUser=userRepository.getUserById(id);
res=userRepository.deleteUser(deleteUser);
}catch (Exception e){
System.out.println("异常信息: "+e.getMessage());
}
return res;
} /**
* 根据name查询是否存在某个user实体
* @param request
* @return
*/
@RequestMapping("/isExistUser")
public Boolean isExistUser(HttpServletRequest request){
Boolean res=false;
try {
String name=request.getParameter("name");
User queryUser=new User(null,Strings.isNullOrEmpty(name)?null:name,null);
User deleteUser=userRepository.getUserByUserName(queryUser);
if (deleteUser!=null){
res=true;
}
}catch (Exception e){
System.out.println("异常信息: "+e.getMessage());
}
return res;
} /**
* 查询user实体的总数
* @return
*/
@RequestMapping("/total")
public Integer getTotal(){
Integer res=;
try {
res=userRepository.getCount();
}catch (Exception e){
System.out.println("异常信息: "+e.getMessage());
}
return res;
} }

至此已经开发完毕了,你可以直接run DemoApplication类,然后在浏览器测试访问,也可以在postman发起访问!下面我才用一键式部署到我的本地tomcat服务器:

完了之后,(当然啦,你也可以jar -jar将你的spring boot打包为jar项目,然后$ java –jar E:\IDEA_Workspace\springbootJDBC\target\demo-0.0.1-SNAPSHOT.jar 也可以直接跑起来)

好了,现在默认就是启动了这个sb项目,下面就开始访问测试各个服务(开头都以 127.0.0.1:8088/)

1,首先是获取用户列表:

2、接着是查询id=3 的user实体:

3、将id=3的实体删除(1:代表操作的记录数-说明已经成功删除)

4、再次查询出来:

5、增加一个user实体:

6、检验一下是否增加该实体成功:

7、更新id=11的实体的相关数据(1:代表更新成功)

8、检验一下是否更新数据成功!

好了,整合完毕!下面提供postman的下载地址(当然了,上面的那些地址其实也可以通过browser进行访问的)

 

spring boot与jdbcTemplate的整合案例2的更多相关文章

  1. Spring Boot数据访问之整合Mybatis

    在Mybatis整合Spring - 池塘里洗澡的鸭子 - 博客园 (cnblogs.com)中谈到了Spring和Mybatis整合需要整合的点在哪些方面,需要将Mybatis中数据库连接池等相关对 ...

  2. Spring Boot 中使用 MyBatis 整合 Druid 多数据源

    2017 年 10 月 20 日   Spring Boot 中使用 MyBatis 整合 Druid 多数据源 本文将讲述 spring boot + mybatis + druid 多数据源配置方 ...

  3. Spring Boot 学习笔记(六) 整合 RESTful 参数传递

    Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...

  4. 史上最全面的Spring Boot Cache使用与整合

    一:Spring缓存抽象 Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口 ...

  5. Spring Boot 集成 FreeMarker 详解案例(十五)

    一.Springboot 那些事 SpringBoot 很方便的集成 FreeMarker ,DAO 数据库操作层依旧用的是 Mybatis,本文将会一步一步到来如何集成 FreeMarker 以及配 ...

  6. 史上最全的Spring Boot Cache使用与整合

    一:Spring缓存抽象# Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接 ...

  7. Spring Boot学习笔记:整合Shiro

    Spring Boot如何和Shiro进行整合: 先自定义一个Realm继承AuthorizingRealm,并实现其中的两个方法,分别对应认证doGetAuthenticationInfo和授权do ...

  8. Spring Boot之JdbcTemplate多数据源配置与使用

    之前在介绍使用JdbcTemplate和Spring-data-jpa时,都使用了单数据源.在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.propertie ...

  9. spring boot(6)-JdbcTemplate访问数据库

     pom.xml 添加jdbc模块和mysql依赖 <dependency> <groupId>org.springframework.boot</groupId&g ...

随机推荐

  1. 关于php加密库加密数据上传数据库或解密出错的问题

    php加密拓展库随着php版本的更新,函数的使用方法有所改变,所以加密模式推荐使用ecb,其中加密算法19种,加密模式8种,通过这种方式加密后的数据上传数据库后提取出来进行解密会发现结果是乱码,我认为 ...

  2. java 通过TCP\UDP 协议实现多人聊天,点对点,文件传送-----分服务器端和客户端

    java 通过TCP\UDP 协议实现多人聊天,点对点,文件传送-----分服务器端和客户端 启动界面如下图: 首先启动服务器: 客户端登陆,登陆成功后为: 默认发送是全部用户,是多人发送. 当在边列 ...

  3. Android 开发笔记___Activity的生命周期

    一个activity就是一个页面,入口函数是oncreate(). onCreate:创建页面,把页面上各个元素加载到内存 onStart:开始页面,把页面显示在屏幕 onResume:恢复页面,让页 ...

  4. 蓝桥杯-算法训练--ALGO-4 结点选择

    本人是一个刚刚接触C++不久的傻学生~记录一些自己的学习过程.大神路过可以批评指正~ 刚学动态规划,水平还很渣,一下子不知道从何下手,借鉴了一下这位大哥的文章 http://www.cnblogs.c ...

  5. 呵呵哒,LNMP下通过fread方式下载文件时,中文名称文件找不到文件

    哎,整整折腾一个下午. 本来好好的,thinkphp 自动的uniq方式保存的文件名,非要使用原文件名,真心蛋疼~~ 然后就只好写个脚本 把原来的所有文件都重新命名一下 - - 然后把数据库对应字段也 ...

  6. Python3学习笔记 - 准备环境

    前言 最近乘着项目不忙想赶一波时髦学习一下Python3.由于正好学习了Docker,并深深迷上了Docker,所以必须趁热打铁的用它来创建我们的Python3的开发测试环境.Python3的中文教程 ...

  7. cursor() — 数据库连接操作 python

    python 操作数据库,要安装一个Python和数据库交互的包MySQL-python-1.2.2.win32-py2.5.exe,然后我们就可以使用MySQLdb这个包进行数据库操作了.      ...

  8. C#中消息的工作流程

    C#中的消息被Application类从应用程序消息队列中取出,然后分发到消息对应的窗体,窗体对象的第一个响应函数是对象中的protected override void WndProc(ref Sy ...

  9. python的Windows下的安装

    1.先打开网址http://www.python.org/download/: 2.在下载列表中选择Window平台安装包, 找到最后 web-based installer 是需要通过联网完成安装的 ...

  10. Science发表的超赞聚类算法

    作者(Alex Rodriguez, Alessandro Laio)提出了一种很简洁优美的聚类算法, 可以识别各种形状的类簇, 并且其超参数很容易确定. 算法思想 该算法的假设是类簇的中心由一些局部 ...