概述
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。 MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs映射成数据库中的记录。
相比Hibernate而言,MyBatis 应该算是半ORM框架,它比Hibernate更灵活,灵活在需要自己写sql语句,当然这是对于那些想自己手动写sql语句的人而言的,因为如何写好sql也是一个很重要的课题。
接下来我们就进入正题,如何整合MyBatis框架
整合MyBatis框架
- 在原先的demo数据库中建表sys_admin_user,并插入测试数据
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for sys_admin_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_admin_user`;
CREATE TABLE `sys_admin_user` (
`admin_user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`user_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '昵称',
`dept_id` bigint(20) DEFAULT NULL COMMENT '部门ID',
`phone` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '电话',
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '电子邮箱',
`avatar` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '头像',
`status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '状态{0:停用,1:正常}',
`deleted_flag` tinyint(1) NOT NULL DEFAULT 0 COMMENT '删除标记{0:未删,1:删除}',
`login_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '最后登陆IP',
`login_time` datetime(0) DEFAULT NULL COMMENT '最后登陆时间',
`created_at` datetime(0) DEFAULT NULL COMMENT '创建时间',
`updated_at` datetime(0) DEFAULT NULL COMMENT '更新时间',
`deleted_at` datetime(0) DEFAULT NULL COMMENT '删除时间',
`created_by` bigint(20) DEFAULT 0 COMMENT '创建者ID',
`updated_by` bigint(20) DEFAULT 0 COMMENT '更新者ID',
`deleted_by` bigint(20) DEFAULT 0 COMMENT '删除者ID',
`remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '' COMMENT '备注',
PRIMARY KEY (`admin_user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of sys_admin_user
-- ----------------------------
INSERT INTO `sys_admin_user` VALUES (1, 'admin', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '卡卡罗特', 1, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '超级管理');
INSERT INTO `sys_admin_user` VALUES (2, 'singlezhang', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '张三', 1, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通管理');
INSERT INTO `sys_admin_user` VALUES (4, 'xiaoli', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '小李', 3, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通员工');
INSERT INTO `sys_admin_user` VALUES (6, 'yiming', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '一鸣', 3, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通员工');
INSERT INTO `sys_admin_user` VALUES (7, 'lisan', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '李三', 4, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通员工');
INSERT INTO `sys_admin_user` VALUES (8, 'laoqian', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '老钱', 3, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通员工');
INSERT INTO `sys_admin_user` VALUES (9, 'xiaomi', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '小米', 5, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通员工');
INSERT INTO `sys_admin_user` VALUES (10, 'jiekema', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '杰克马', 5, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通员工');
INSERT INTO `sys_admin_user` VALUES (11, 'misschen', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '小陈', 4, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通员工');
INSERT INTO `sys_admin_user` VALUES (12, 'jiekema2', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '杰克马2', 3, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通员工');
INSERT INTO `sys_admin_user` VALUES (13, 'jiekema3', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '杰克马3', 3, '123456', 'admin@qq.com', NULL, 1, 0, '127.0.0.1', '2020-10-17 16:16:11', '2020-10-17 16:16:16', '2020-10-17 16:16:18', NULL, 0, 0, 0, '普通员工');
SET FOREIGN_KEY_CHECKS = 1;
- 在 pom.xml中添加mybatis依赖(文中只涉及本文相关依赖,其他的依赖在前文中参考)
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- SpringBoot集成mybatis框架 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.boot.version}</version>
</dependency>
3.使用mybatis-generator插件生成 DAO,Model,XML映射文件,如下图:
※说明:关于mybatis-generator插件的使用,可以在《如何使用mybatis-generator插件,自动生成mybatis相关文件》一文中了解。
4.添加MyBatis配置类:MybatisConfig.java
package com.zhlab.demo.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
* @ClassName MybatisConfig
* @Description //MybatisConfig配置类
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2020/10/31 0031 上午 9:37
**/
@Configuration
@MapperScan("com.zhlab.demo.mapper") //mapper
public class MybatisConfig {
@Autowired
private DataSource dataSource;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage("com.zhlab.demo.model"); // model
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sessionFactory.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml")); // 扫描映射文件
return sessionFactory.getObject();
}
}
- 在DAO层的SysAdminUserMapper.java中添加selectAll()
package com.zhlab.demo.mapper;
import com.zhlab.demo.model.SysAdminUser;
import java.util.List;
public interface SysAdminUserMapper {
int insert(SysAdminUser record);
// 获取用户列表
List<SysAdminUser> selectAll();
}
- 在对应的xml映射文件SysAdminUserMapper.xml中增加selectAll
<mapper namespace="com.zhlab.demo.mapper.SysAdminUserMapper">
<resultMap id="SysAdminUserResult" type="SysAdminUser">
<result column="admin_user_id" jdbcType="BIGINT" property="adminUserId" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="nick_name" jdbcType="VARCHAR" property="nickName" />
<result column="dept_id" jdbcType="BIGINT" property="deptId" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="avatar" jdbcType="VARCHAR" property="avatar" />
<result column="status" jdbcType="BIT" property="status" />
<result column="deleted_flag" jdbcType="BIT" property="deletedFlag" />
<result column="login_ip" jdbcType="VARCHAR" property="loginIp" />
<result column="login_time" jdbcType="TIMESTAMP" property="loginTime" />
<result column="created_at" jdbcType="TIMESTAMP" property="createdAt" />
<result column="updated_at" jdbcType="TIMESTAMP" property="updatedAt" />
<result column="deleted_at" jdbcType="TIMESTAMP" property="deletedAt" />
<result column="created_by" jdbcType="BIGINT" property="createdBy" />
<result column="updated_by" jdbcType="BIGINT" property="updatedBy" />
<result column="deleted_by" jdbcType="BIGINT" property="deletedBy" />
<result column="remark" jdbcType="VARCHAR" property="remark" />
</resultMap>
<select id="selectAll" parameterType="SysAdminUser" resultMap="SysAdminUserResult">
select u.*
from sys_admin_user u
</select>
</mapper>
- 在service层增加SysAdminUserService.java,并调用DAO层中SysAdminUserMapper的方法
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName SysAdminUserService
* @Description //TODO
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2020/10/31 0031 上午 9:45
**/
@Service
public class SysAdminUserService {
@Autowired
SysAdminUserMapper sysAdminUserMapper;
// 获取用户列表
public List<SysAdminUser> findAll(){
return sysAdminUserMapper.selectAll();
}
}
- 在接口层创建一个UserController.java,来测试一下
package com.zhlab.demo.controller;
import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.service.SysAdminUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @ClassName UserController
* @Description //TODO
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2020/10/31 0031 上午 9:43
**/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
SysAdminUserService sysAdminUserService;
/* 方法注解 */
@ApiOperation(value = "方法名:用户列表", notes = "获取用户列表")
@GetMapping("/list")
public List<SysAdminUser> list(){
List<SysAdminUser> list = sysAdminUserService.findAll();
return list;
}
}
-
运行项目,打开http://localhost:8080/swagger-ui.html看执行效果
-
运行这个接口,可以得到想要的所有用户的列表
总结
Mybatis的集成还是比较简单的,后续还会讲解分页以及复杂查询,对于插件的使用可以选择一种mybatis-generator或者mybatis-plus,两种不可同时使用,会发生冲突。