Spring Boot 集成 MyBatis和 SQL Server实践
概 述
Spring Boot工程集成 MyBatis来实现 MySQL访问的示例我们见过很多,而最近用到了微软的 SQL Server数据库,于是本文则给出一个完整的 Spring Boot + MyBatis + SQL Server 的工程示例。
注: 本文首发于 My Personal Blog:CodeSheep·程序羊,欢迎光临 小站
工程搭建
- 新建 Spring Boot工程
pom.xml中添加 MyBatis和 SQL Server相关的依赖
<!--for mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--for SqlServer-->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
复制代码
- 配置
application.properties
这里同样主要是对于 MyBatis 和 SQL Server连接相关的配置
server.port=89
# mybatis 配置
mybatis.type-aliases-package=cn.codesheep.springbt_mybatis_sqlserver.entity
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
## -------------------------------------------------
## SqlServer 配置
spring.datasource.url=jdbc:sqlserver://xxxx:1433;databasename=MingLi
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.username=xxxx
spring.datasource.password=xxxx
复制代码
建立 SQL Server数据表和实体类
- 首先在 SQL Server数据库中新建数据表
user_test作为测试用表
DROP TABLE [demo].[user_test]
GO
CREATE TABLE [dbo].[user_test] (
[user_id] int NOT NULL ,
[user_name] varchar(50) NOT NULL ,
[sex] tinyint NOT NULL ,
[created_time] varchar(50) NOT NULL
)
GO
复制代码
- 然后在我们的工程中对应建立的
User实体类
其字段和实际数据表的字段一一对应
public class User {
private Long userId;
private String userName;
private Boolean sex;
private String createdTime;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
public String getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
}
复制代码
Mybatis Mapper映射配置
- MyBatis映射配置的 XML文件如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.codesheep.springbt_mybatis_sqlserver.mapper.UserMapper">
<resultMap id="userMap" type="cn.codesheep.springbt_mybatis_sqlserver.entity.User">
<id property="userId" column="user_id" javaType="java.lang.Long"></id>
<result property="userName" column="user_name" javaType="java.lang.String"></result>
<result property="sex" column="sex" javaType="java.lang.Boolean"></result>
<result property="createdTime" column="created_time" javaType="java.lang.String"></result>
</resultMap>
<select id="getAllUsers" resultMap="userMap">
select * from user_test
</select>
<insert id="addUser" parameterType="cn.codesheep.springbt_mybatis_sqlserver.entity.User">
insert into user_test ( user_id, user_name, sex, created_time ) values ( #{userId}, #{userName}, #{sex}, #{createdTime} )
</insert>
<delete id="deleteUser" parameterType="cn.codesheep.springbt_mybatis_sqlserver.entity.User">
delete from user_test where user_name = #{userName}
</delete>
</mapper>
复制代码
- 与此同时,这里也给出对应 XML的 DAO接口
public interface UserMapper {
List<User> getAllUsers();
int addUser( User user );
int deleteUser( User user );
}
复制代码
为了试验起见,这里给出了 增 / 删 / 查 三个数据库操作动作。
编写 Service 和测试Controller
- 上面这些准备工作完成之后,接下来编写数据库 CRUD的 Service类
@Service
@Primary
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
@Override
public int addUser(User user) {
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
user.setCreatedTime( form.format(new Date()) );
return userMapper.addUser( user );
}
@Override
public int deleteUser(User user) {
return userMapper.deleteUser( user );
}
}
复制代码
这里的 Service功能同样主要关于数据表的 增 / 删 / 查 三个数据库操作动作。
- 对照着上面的Service,我们编写一个对应接口测试的Controller
@RestController
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping(value = "/getAllUser", method = RequestMethod.GET)
public List<User> getAllUser() {
return userService.getAllUsers();
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public int addUser( @RequestBody User user ) {
return userService.addUser( user );
}
@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
public int deleteUser( @RequestBody User user ) {
return userService.deleteUser( user );
}
}
复制代码
实验测试
- 插入数据
依次用 POSTMAN通过 Post /addUser接口插入三条数据:
{"userId":1,"userName":"刘能","sex":true}
{"userId":2,"userName":"赵四","sex":false}
{"userId":3,"userName":"王大拿","sex":true}
复制代码
插入完成后去 SQL Server数据库里看一下数据插入情况如下:
- 查询数据
调用 Get /getAllUser接口,获取刚插入的几条数据
- 删除数据
调用 Post /deleteUser接口,可以通过用户名来删除对应的用户
后 记
作者:CodeSheep
链接:https://juejin.im/post/5c1837ff6fb9a049d1320d76
Spring Boot 集成 MyBatis和 SQL Server实践的更多相关文章
- spring boot集成mybatis只剩两个sql 并提示 Cannot obtain primary key information from the database, generated objects may be incomplete
前言 spring boot集成mybatis时只生成两个sql, 搞了一个早上,终于找到原因了 找了很多办法都没有解决, 最后注意到生成sql的时候打印了一句话: Cannot obtain pri ...
- 【spring boot】14.spring boot集成mybatis,注解方式OR映射文件方式AND pagehelper分页插件【Mybatis】pagehelper分页插件分页查询无效解决方法
spring boot集成mybatis,集成使用mybatis拖沓了好久,今天终于可以补起来了. 本篇源码中,同时使用了Spring data JPA 和 Mybatis两种方式. 在使用的过程中一 ...
- spring boot集成mybatis(1)
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot集成mybatis(2) - 使用pagehelper实现分页
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- Spring Boot集成MyBatis开发Web项目
1.Maven构建Spring Boot 创建Maven Web工程,引入spring-boot-starter-parent依赖 <project xmlns="http://mav ...
- 详解Spring Boot集成MyBatis的开发流程
MyBatis是支持定制化SQL.存储过程以及高级映射的优秀的持久层框架,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集. spring Boot是能支持快速创建Spring应用的Java框 ...
- 【spring boot】【mybatis】spring boot中mybatis打印sql语句
spring boot中mybatis打印sql语句,怎么打印出来?[参考:https://www.cnblogs.com/sxdcgaq8080/p/9100178.html] 在applicati ...
- spring boot集成mybatis(3) - mybatis generator 配置
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot集成MyBatis 通用Mapper 使用总结
spring boot集成MyBatis 通用Mapper 使用总结 2019年 参考资料: Spring boot集成 MyBatis 通用Mapper SpringBoot框架之通用mapper插 ...
随机推荐
- soap 简单的例子
首先确保你的soap模块开启 客户端代码 <?php try { $client = new SoapClient(null, array('location' =>"http: ...
- (暂时弃坑)(半成品)ACM数论之旅18---反演定理 第二回 Mobius反演(莫比乌斯反演)((づ ̄3 ̄)づ天才第一步,雀。。。。)
莫比乌斯反演也是反演定理的一种 既然我们已经学了二项式反演定理 那莫比乌斯反演定理与二项式反演定理一样,不求甚解,只求会用 莫比乌斯反演长下面这个样子(=・ω・=) d|n,表示n能够整除d,也就是d ...
- Python学习笔记day01--Python基础
1 python的应用 Python崇尚优美.清晰.简单,是一个优秀并广泛使用的语言. Python可以应用于众多领域,如:数据分析.组件集成.网络服务.图像处理.数值计算和科学计算等 ...
- java 数据结构与算法---树
一.树的概念 除根节点外,其余节点有且只有一个父节点. 1.度 节点的度:每个节点的子节点个数. 树的度:树内各个节点的度的最大值. 树的高度(深度):树中节点的最大层次称为树的深度. 节点路径:一 ...
- linux中创建和解压文档的 tar 命令教程
linux & zip & tar https://www.cnblogs.com/xgqfrms/p/9714161.html 1 linux中的tar命令 tar(磁带归档)命令是 ...
- PGM学习之六 从有向无环图(DAG)到贝叶斯网络(Bayesian Networks)
本文的目的是记录一些在学习贝叶斯网络(Bayesian Networks)过程中遇到的基本问题.主要包括有向无环图(DAG),I-Maps,分解(Factorization),有向分割(d-Separ ...
- Callable 和 Runnable 的区别
Callable 和 Runnable 的使用方法大同小异, 区别在于: 1.Callable 使用 call() 方法, Runnable 使用 run() 方法 2.call() 可以返回值, 而 ...
- Jmeter—添加断言 判断接口响应数据是否符合预期
发出请求之后,通过添加断言可以判断响应数据是否是我们的预期结果. 1 在Jmeter中发送一个状态返回200的http请求(参数故意输入错误).结果肯定是不是返回200啦. 但结果树中http请求的图 ...
- Vivian's Problem UVA - 1323(梅林素数+状压二进制)
借鉴:https://blog.csdn.net/miku23736748/article/details/52135932 https://blog.csdn.net/acm_cxlove/arti ...
- 【BZOJ4903/UOJ300】【CTSC2017】吉夫特
Description 传送门 简述题意:给一个序列,询问有多少子序列满足其中不会出现\(a\choose b\)是偶数的情况,其中\(a\)在\(b\)前面. Solution 首先探究组合数的 ...