作者:追梦1819

原文:https://www.cnblogs.com/yanfei1819/p/10869315.html

版权声明:本文为博主原创文章,转载请附上博文链接!

## 引言

  ORM框架有很多,比如Mybatis、hibernate、JPA、JDBCTemplate等,各自有各自的优点。Mybatis作为一个半自动的框架,灵活易上手等特点,收到了很多人的青睐。

  本文介绍springboot 集成 Mybatis框架。

Mybatis介绍

基本概念

  什么是 Mybatis?

  官方给的解释是:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

优缺点

  Mybatis 可能是用的最广泛的一个 ORM 框架了,下面简单列举其优缺点。

优点:

  • 易上手;
  • sql 灵活,与代码解耦;
  • 支持对象与数据库映射;
  • 半自动框架,灵活性较高;

缺点:

  • 需要维护 sql ;

  • 绑定了sql,移植性差;

  • 二级缓存机制不佳;

开发模式

准备工作

  在Mybatis 中,有两种方式开发方式:配置文件开发和注解开发,以下分别介绍两种模式。

  我们先来做一下准备工作。不管是哪一种开发模式,下面几步都是相同的:

  1. 都需要对 Mybatis 代理接口进行扫描。在 SpringBoot 项目中,扫描方式有两种:

1) 在启动类上加 @MapperScan(value = {"com.sunwin.db.*","com.yanfei1819.mybatisdemo.db"}) 注解;

2) 分别在接口 mapper 上添加 @Mapper 注解;

  上面扫描Mybatis 代理接口的两种方式的效果一样,只不过第一种方式是一次性扫描整个包,第二种方式是单独扫描每个接口。

  1. 初始化数据库:

    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    `age` int(3) NOT NULL,
    PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 50 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES (14, 'admin', 21);
    INSERT INTO `user` VALUES (48, 'teacher', 20);
    INSERT INTO `user` VALUES (49, 'student', 22); SET FOREIGN_KEY_CHECKS = 1;
  2. 引入maven 依赖:

    <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.1</version>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency> <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
    </dependency>
  3. 配置数据库信息:

    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://192.168.1.88:3306/win_health?serverTimezone=GMT%2B8
    spring.datasource.username=root
    spring.datasource.password=pass123

注解开发

  开发之前,先大体了解一下项目的结构(这个结构都是自定义的,这里只是为了演示方便):

  首先,创建一个实体类:

package com.yanfei1819.mybatisdemo.db.dto;

/**
* Created by 追梦1819 on 2019-05-05.
*/
public class UserDto {
private Long id;
private String name;
private int age;
// set/get 省略
}

  创建以下实体类是为了试返回的值展示更加友好。

package com.yanfei1819.mybatisdemo.entity;
import com.yanfei1819.mybatisdemo.db.dto.UserDto;
import java.util.List; /**
* Created by 追梦1819 on 2019-05-05.
*/
public class UserListResponse {
private int code;
private String msg;
private List<UserDto> users;
// set/get 省略
}

  其次,创建代理接口:

package com.yanfei1819.mybatisdemo.db.dao;
import com.yanfei1819.mybatisdemo.db.dto.UserDto;
import org.apache.ibatis.annotations.Select; import java.util.List;
/**
* Created by 追梦1819 on 2019-05-05.
*/
public interface UserDao {
@Select("select * from user ")
List<UserDto> queryList();
}

  再者,创建service层:

package com.yanfei1819.mybatisdemo.service;
import com.yanfei1819.mybatisdemo.entity.UserListResponse; /**
* Created by 追梦1819 on 2019-05-05.
*/
public interface UserService {
UserListResponse queryUsers();
}
package com.yanfei1819.mybatisdemo.service.impl;
import com.yanfei1819.mybatisdemo.db.dao.UserDao;
import com.yanfei1819.mybatisdemo.db.dto.UserDto;
import com.yanfei1819.mybatisdemo.entity.UserListResponse;
import com.yanfei1819.mybatisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; /**
* Created by 追梦1819 on 2019-05-05.
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public UserListResponse queryUsers() {
List<UserDto> userDtos = userDao.queryList();
UserListResponse response = new UserListResponse();
response.setUsers(userDtos);
response.setCode(0);
response.setMsg("success");
return response;
}
}

  然后,创建controller层:

package com.yanfei1819.mybatisdemo.controller;
import com.yanfei1819.mybatisdemo.entity.UserListResponse;
import com.yanfei1819.mybatisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody; /**
* Created by 追梦1819 on 2019-05-05.
*/
@Controller
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@GetMapping("/queryUsers")
public UserListResponse queryUsers(){
return userService.queryUsers();
}
}

  最后,启动main 方法:

package com.yanfei1819.mybatisdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("com.yanfei1819.mybatisdemo.db") // 注意这个注解
public class MybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisDemoApplication.class, args);
} }

  用postman测试:

配置文件开发

  配置文件模式开发比注解开发稍稍复杂一点。因为这种模式多了维护 sql 的 mapper.xml 文件。我将其归结为下面三步:

  1. 创建代理接口:

  2. 创建接口映射的 xxxMapper.xml 文件

  3. 在主配置文件 application.properties 中指定 xxxMapper.xml 的位置: mybatis.mapper-locations=classpath:mapper/*.xml

  在以上项目的基础上,添加以下代码。

  首先,新建实体类:

package com.yanfei1819.mybatisdemo.entity;
import com.yanfei1819.mybatisdemo.db.dto.UserDto; /**
* Created by 追梦1819 on 2019-05-05.
*/
public class UserResponse {
private int code;
private String msg;
private UserDto user;
}

  其次,创建mapper接口:

package com.yanfei1819.mybatisdemo.db.mapper;
import com.yanfei1819.mybatisdemo.db.dto.UserDto;
import org.apache.ibatis.annotations.Param;
/**
* Created by 追梦1819 on 2019-05-05.
*/
public interface UserMapper {
UserDto queryUserByName(@Param("name") String name);
}

  然后,创建UserMapper文件:

<?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="com.yanfei1819.mybatisdemo.db.mapper.UserMapper">
<select id="queryUserByName" resultType="com.yanfei1819.mybatisdemo.db.dto.UserDto" parameterType="java.lang.String">
select * from user where `name` = #{name}
</select>
</mapper>

  下面,UserService 接口添加方法:

UserResponse queryUserByName(String name);

  UserServiceImpl 类实现:

    @Override
public UserResponse queryUserByName(String name){
UserDto userDto = userMapper.queryUserByName(name);
UserResponse response = new UserResponse();
response.setUser(userDto);
response.setCode(0);
response.setMsg("success");
return response;
}

  最后,在 controller 层添加方法:

    @ResponseBody
@GetMapping("/queryUserByName")
public UserResponse queryUserByName(String name){
return userService.queryUserByName(name);
}

  测试结果

总结

  针对上面两种方式,各有优势。注解开发基本上只要@Insert@Select@Update@Delete 四个注解就可以搞定。配置文件开发只需要在 xxxMapper.xml 维护 sql 即可。

  我个人的喜好是,如果是单表操作,或者是工具包,就选择注解方式,因为比较简洁,没有配置文件;如果是多表操作,则选择配置文件的方式,对sql的操作更灵活,扩展性更好。

  源码:我的GitHub

<全文完>



更多精彩,请关注公众号:【技术与人生】

SpringBoot第五篇:整合Mybatis的更多相关文章

  1. Springboot 2.0.4 整合Mybatis出现异常Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

    在使用Springboot 2.0.4 整合Mybatis的时候出现异常Property 'sqlSessionFactory' or 'sqlSessionTemplate' are require ...

  2. SpringBoot数据访问之整合mybatis注解版

    SpringBoot数据访问之整合mybatis注解版 mybatis注解版: 贴心链接:Github 在网页下方,找到快速开始文档 上述链接方便读者查找. 通过快速开始文档,搭建环境: 创建数据库: ...

  3. (入门SpringBoot)SpringBoot项目数据源以及整合mybatis(二)

    1.配置tomcat数据源: #   数据源基本配置spring.datasource.url=jdbc:mysql://localhost:3306/shoptest?useUnicode=true ...

  4. SpringBoot学习- 3、整合MyBatis

    SpringBoot学习足迹 1.下载安装一个Mysql数据库及管理工具,同类工具很多,随便找一个都可以,我在windows下做测试项目习惯使用的是haosql 它内部集成了MySql-Front管理 ...

  5. SpringBoot数据访问之整合Mybatis配置文件

    环境搭建以及前置知识回顾 SpringBoot中有两种start的形式: 官方:spring-boot-starter-* 第三方:*-spring-boot-starter Mybatis属于第三方 ...

  6. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  7. Springboot第五篇:结合myBatis进行SQL操作

    前提:和之前同样的,本篇会从前端和后台一起讲述关于SQL的select操作(其他操作原理大致类似,不多做解释了). 大致流程:前端通过AJAX将数据发送到后台的路由,后台路由会根据发送的数据进行SQL ...

  8. Mybatis第五篇【Mybatis与Spring整合】

    Mybatis与Spring整合 既然我们已经学了Mybatis的基本开发了,接下来就是Mybatis与Spring的整合了! 以下使用的是Oracle数据库来进行测试 导入jar包 aopallia ...

  9. SpringBoot Maven多模块整合MyBatis 打包jar

    最近公司开始新的项目,框架选定为SpringBoot+Mybatis,本篇主要记录了在IDEA中搭建SpringBoot多模块项目的过程. 源码:https://github.com/12641561 ...

随机推荐

  1. 如何处理异常? catch Exception OR catch Throwable

    在Java中,当你需要统一处理异常的时候,你是会选择catch (Exception),还是直接catch (Throwable)? Java的异常体系 Throwable: Java中所有异常和错误 ...

  2. java.io.InvalidClassException 异常解决, 实现Serializable接口的注意事项

    解决方案: 在类中显式指定 private static final long serialVersionUID = 42L; 类实现序列化接口, 进行序列化反序列化的时候, 抛出 java.io.I ...

  3. Eclipse_常用技巧_02_使用Eclipse进行源码分析

    1.分析java类和接口的继承关系 具体做法: 在代码区中选择需要的类和接口定义,然后右击,选择“Open Type Hiberarchy”,可以在“Hiberarchy View”中看到继承关系 快 ...

  4. BEC listen and translation exercise 40

    However, recently there's been more and more interest in the development of ostrich farming in other ...

  5. Leetcode 1002. Find Common Characters

    python可重集合操作 class Solution(object): def commonChars(self, A): """ :type A: List[str] ...

  6. C语言小程序(五)、数组查询

    随机产生一些字符,然后输入要查找的字符,本想将查找到的字符存储起来,要么初始化一个等大小的数组,要么要先检索出总共查找到多少个元素,再开辟空间存储,但这样相当于搜索了两遍,没有想到更好的方法,只是简单 ...

  7. ffpanel --ffmpeg的GUI,让ffmpeg离开黑黑的命令行

    程序及源码下载地址 :https://github.com/langsim/ffpanel   from:http://blog.csdn.net/langsim/article/details/47 ...

  8. spring IOC 注解@Autowired

    自动装配:按照类型来找 会在xml中找类型一样的, 比如 setMessage(SetName setName)上面有@Autowired,会到xml中找<bean id="setna ...

  9. 江苏省大学生程序设计竞赛(JSCPC)赛后感

    仔细的算了一下,这是我第6次参加与acm有关的比赛了,每一次的经历,在我看来都是一次对自己能力的认识与评估,身边学计算机专业的同龄人对这项比赛的热爱,专注,勇气以及所获得的成就让要好好努力,更要加倍付 ...

  10. Linker Tools Error LNK2001

    https://msdn.microsoft.com/en-us/library/f6xx1b1z.aspx https://www.cnblogs.com/runningRain/p/5674833 ...