Spring Boot 2.X(二):集成 MyBatis 数据层开发
MyBatis 简介
概述
MyBatis 是一款优秀的持久层框架,支持定制化 SQL、存储过程以及高级映射。它采用面向对象编程的方式对数据库进行 CRUD 的操作,使程序中对关系数据库的操作更方便简单。它支持 XML 描述符配置文件和注解两种方式执行 SQL 语句。“简单灵活”是它在对象关系映射工具上的最大优势。
mybatis-spring-boot-starter
过去使用 MyBatis 开发,需要各种配置文件、实体类、Dao 层映射关联、还有一大推其它配置。经过进行不断的优化后,终于他来了,mybatis-spring-boot-starter
可以做到无需配置只用注解开发,也可以使用简单的配置轻松上手。
当然两种方式都需要在 POM 文件引入mybatis-spring-boot-starter
:
<!-- mybaits -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
集成 MyBatis
准备工作
1.构建一个 Spring Boot项目
2.建立 MySQL 数据库(db_test),创建表(t_user)及添加部分测试数据
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(8) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户姓名',
`user_sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户性别',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_user
-- ----------------------------
BEGIN;
INSERT INTO `t_user` VALUES (1, '刘备', '男');
INSERT INTO `t_user` VALUES (2, '孙尚香', '女');
INSERT INTO `t_user` VALUES (3, '周瑜', '男');
INSERT INTO `t_user` VALUES (4, '小乔', '女');
INSERT INTO `t_user` VALUES (5, '诸葛亮', '男');
INSERT INTO `t_user` VALUES (6, '黄月英', '女');
INSERT INTO `t_user` VALUES (7, '关羽', '男');
INSERT INTO `t_user` VALUES (8, '张飞', '男');
INSERT INTO `t_user` VALUES (9, '赵云', '男');
INSERT INTO `t_user` VALUES (10, '黄总', '男');
INSERT INTO `t_user` VALUES (11, '曹操', '男');
INSERT INTO `t_user` VALUES (12, '司马懿', '男');
INSERT INTO `t_user` VALUES (13, '貂蝉', '女');
INSERT INTO `t_user` VALUES (14, '吕布', '男');
INSERT INTO `t_user` VALUES (15, '马超', '男');
INSERT INTO `t_user` VALUES (16, '魏延', '男');
INSERT INTO `t_user` VALUES (17, '孟获', '男');
INSERT INTO `t_user` VALUES (18, '大乔', '女');
INSERT INTO `t_user` VALUES (19, '刘婵', '男');
INSERT INTO `t_user` VALUES (20, '姜维', '男');
INSERT INTO `t_user` VALUES (21, '廖化', '男');
INSERT INTO `t_user` VALUES (22, '关平', '男');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
3.新建用户实体类 UserEntity.java
public class UserEntity {
private Long id;
private String userName;
private String userSex;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
}
注解方式
1.添加相关 Maven 依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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-starter-jdbc</artifactId>
</dependency>
<!-- 热部署模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
</dependency>
<!-- mysql 数据库驱动. -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- mybaits -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>
2.application.properties 添加相关配置
#datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
在启动类中添加对 mapper 包扫描@MapperScan
@SpringBootApplication
@MapperScan("cn.zwqh.springboot.dao")
public class SpringBootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisApplication.class, args);
}
}
或者直接在 Mapper 类上面添加注解@Mapper,建议使用上面那种,不然每个 mapper 加个注解也挺麻烦的
3.Mapper 开发
public interface UserDao {
//使用注解方式
/**
* 获取所有用户
* @return
*/
@Select("select * from t_user")
@Results({
@Result(property = "userName",column = "user_name"),
@Result(property = "userSex",column = "user_sex")
})
List<UserEntity> getAll2();
/**
* 根据id获取用户
* @param id
* @return
*/
@Select("select * from t_user where id=#{id}")
@Results({
@Result(property = "userName",column = "user_name"),
@Result(property = "userSex",column = "user_sex")
})
List<UserEntity> getOne2(Long id);
/**
* 新增用户
* @param user
*/
@Insert("insert into t_user (user_name,user_sex) values(#{userName},#{userSex})")
void insertUser2(UserEntity user);
/**
* 修改用户
* @param user
*/
@Update("update t_user set user_name=#{userName},user_sex=#{userSex} where id=#{id}")
void updateUser2(UserEntity user);
/**
* 删除用户
* @param id
*/
@Delete("delete from t_user where id=#{id}")
void deleteUser2(Long id);
}
注解:
@Select 是查询类的注解,所有的查询均使用这个
@Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
@Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
@Update 负责修改,也可以直接传入对象
@delete 负责删除
4. restful 接口测试
UserController
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserDao userDao;
//使用注解方式
/**
* 获取所有用户
* @return
*/
@RequestMapping("/getAll2")
public List<UserEntity> getAll2(){
return userDao.getAll2();
}
/**
* 根据id获取用户
* @return
*/
@RequestMapping("/getOne2")
public List<UserEntity> getOne2(Long id){
return userDao.getOne2(id);
}
/**
* 新增用户
* @param user
* @return
*/
@RequestMapping("/insertUser2")
public String insertUser2(UserEntity user) {
userDao.insertUser2(user);
return "insert success";
}
/**
* 修改用户
* @param user
* @return
*/
@RequestMapping("/updateUser2")
public String updateUser2(UserEntity user) {
userDao.updateUser2(user);
return "update success";
}
/**
* 删除用户
* @param user
* @return
*/
@RequestMapping("/deleteUser2")
public String deleteUser2(Long id) {
userDao.deleteUser2(id);
return "delete success";
}
}
启动项目后可以通过浏览器访问 http://127.0.0.1:8080/user/getOne2?id=1
进行测试,其他雷同。也可以编写单元测试进行测试。
XML 方式
1.pom 文件如上
2.application.properties 添加相关配置
#datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
#mybatis
mybatis.mapper-locations=classpath:/mapper/*.xml
3.Mapper 层开发
public interface UserDao {
//mapper.xml方式
/**
* 获取所有用户
* @return
*/
List<UserEntity> getAll();
/**
* 根据id获取用户
* @return
*/
List<UserEntity> getOne(Long id);
/**
* 新增用户
* @param user
*/
void insertUser(UserEntity user);
/**
* 修改用户
* @param user
*/
void updateUser(UserEntity user);
/**
* 删除用户
* @param id
*/
void deleteUser(Long id);
}
4.xml 映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.zwqh.springboot.dao.UserDao">
<resultMap type="cn.zwqh.springboot.model.UserEntity" id="user">
<id property="id" column="id"/>
<result property="userName" column="user_name"/>
<result property="userSex" column="user_sex"/>
</resultMap>
<!-- 获取所有用户 -->
<select id="getAll" resultMap="user">
select * from t_user
</select>
<!-- 根据用户ID获取用户 -->
<select id="getOne" resultMap="user">
select * from t_user where id=#{id}
</select>
<!-- 新增用户 -->
<insert id="insertUser" parameterType="cn.zwqh.springboot.model.UserEntity">
insert into t_user (user_name,user_sex) values(#{userName},#{userSex})
</insert>
<!-- 修改用户 -->
<update id="updateUser" parameterType="cn.zwqh.springboot.model.UserEntity">
update t_user set user_name=#{userName},user_sex=#{userSex} where id=#{id}
</update>
<!-- 删除用户 -->
<delete id="deleteUser" parameterType="Long">
delete from t_user where id=#{id}
</delete>
</mapper>
如何选择使用
个人觉得,注解方式适合轻量级的项目,现在的微服务项目比较适合这种模式;对于大型项目,复杂的多表联合查询sql用 xml 更适合。
扩展: 使用 MyBatis 分页插件 pagehelper
1. pom.xml 添加依赖
<!-- pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
2. pagehelper 使用
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserDao userDao;
/**
* 使用pagehelper分页插件
* @param pageNum
* @param pageSize
* @return
*/
@RequestMapping("/pagehelperTest")
public List<UserEntity> pagehelperTest(int pageNum,int pageSize){
PageHelper.startPage(pageNum, pageSize);
return userDao.getAll(); //直接使用上面的 mapper
}
}
3. 测试
浏览器直接访问 http://127.0.0.1:8080/user/pagehelperTest?pageNum=1&pageSize=10
,改变参数试试。
示例代码
非特殊说明,本文版权归 朝雾轻寒 所有,转载请注明出处.
原文标题: Spring Boot 2.X(二):集成 MyBatis 数据层开发
原文地址:https://www.zwqh.top/article/info/3
如果文章对您有帮助,请扫码关注下我的公众号,文章持续更新中...
Spring Boot 2.X(二):集成 MyBatis 数据层开发的更多相关文章
- Spring Boot 项目学习 (二) MySql + MyBatis 注解 + 分页控件 配置
0 引言 本文主要在Spring Boot 基础项目的基础上,添加 Mysql .MyBatis(注解方式)与 分页控件 的配置,用于协助完成数据库操作. 1 创建数据表 这个过程就暂时省略了. 2 ...
- Spring Boot(六)集成 MyBatis 操作 MySQL 8
一.简介 1.1 MyBatis介绍 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集. ...
- Spring boot后台搭建二集成Shiro实现用户验证
上一篇文章中介绍了Shiro 查看 将Shiro集成到spring boot的步骤: (1)定义一个ShiroConfig,配置SecurityManager Bean,SecurityManager ...
- Spring Boot简单xml配置集成mybatis
一.xml配置版 1.properties文件中增加的配置: mybatis.config-locations=classpath:mybatis/mybatis-config.xml mybatis ...
- Spring boot后台搭建二集成Shiro权限控制
上一篇文章,实现了用户验证 查看,接下来实现下权限控制 权限控制,是管理资源访问的过程,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等 Apache Shir ...
- Spring boot后台搭建二集成Shiro添加Remember Me
上一片文章实现了用户验证 查看 当用户成功登录后,关闭浏览器,重新打开浏览器访问http://localhost:8080,页面会跳转到登录页,因为浏览器的关闭后之前的登录已失效 Shiro提供了R ...
- Spring boot 梳理 - 配置eclipse集成maven,并开发Spring boot hello
@RestController @EnableAutoConfiguration public class App { @RequestMapping("/hello") publ ...
- 学习Spring Boot:(二十五)使用 Redis 实现数据缓存
前言 由于 Ehcache 存在于单个 java 程序的进程中,无法满足多个程序分布式的情况,需要将多个服务器的缓存集中起来进行管理,需要一个缓存的寄存器,这里使用的是 Redis. 正文 当应用程序 ...
- Spring Boot下Druid连接池+mybatis
目前Spring Boot中默认支持的连接池有dbcp,dbcp2, hikari三种连接池. 引言: 在Spring Boot下默认提供了若干种可用的连接池,Druid来自于阿里系的一个开源连 ...
随机推荐
- CF1005D Polycarp and Div 3 思维
Polycarp and Div 3 time limit per test 3 seconds memory limit per test 256 megabytes input standard ...
- CF991D Bishwock 第十七 贪心
Bishwock time limit per test 1 second memory limit per test 256 megabytes input standard input outpu ...
- CF990B Micro-World 贪心 第十六
Micro-World time limit per test 2 seconds memory limit per test 256 megabytes input standard input o ...
- HDU 5793 A Boring Question 多校训练
There are an equation. ∑0≤k1,k2,⋯km≤n∏1⩽j<m(kj+1kj)%1000000007=?∑0≤k1,k2,⋯km≤n∏1⩽j<m(kj+1kj)%1 ...
- Java 添加Word文本框
在Word中,文本框是指一种可移动.可调节大小的文字或图形容器.我们可以向文本框中添加文字.图片.表格等对象,下面,将通过Java编程来实现添加以上对象到Word文本框. 使用工具:Free Spir ...
- 【LeetCode】[0001] 【两数之和】
题目描述 思路分析 Java代码 代码链接 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个整数,并返回他们的数组下标.你可以假设每种输入只会对 ...
- Oracle sqlldr 在DOS窗口导入多列数据到数据库表
sqlldr 用法详见:https://www.cnblogs.com/rootq/archive/2009/03/01/1401061.html 测试内容: 1.创建数据库表: create tab ...
- SQLi_LABS less5: GET-Double Injection - Single Quotes - String
目录 前言 几种可能的注入方式 补充的相关知识点 前言 最近开始用SQLi_LABS学习注入,刚开始有点摸不到头脑,索性把看到的知识点记录下来,很多细节是看别人博客学的,就直接给链接了,在此向这些作者 ...
- Python(Head First)学习笔记:六
6 定制数据对象:数据结构自定义 打包代码与数据 james2.txt: James Lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-2 ...
- 通过Service访问应用 (2)
目录 通过NodePort Service在外部访问集群应用 通过LoadBalancer Service在外部访问集群应用 Microsoft SQL Server数据库部署 为了便于理解和学习,请 ...