Spring集成Mybatis-plus

8次阅读

共计 3899 个字符,预计需要花费 10 分钟才能阅读完成。

Springboot 中流行的持久层框架是 Hibernate 和 Mybatis

前者已经成为 Spring Data 的规范, 以极简和全自动的对象映射著称, 后者是一个半自动化的 ORM 框架,SQL 独立存放在 XML 文件中, 提高自由度的同时也方便 DBA 进行校对和后续 SQL 优化

由于 Mybatis plus 完全基于 Mybatis, 且吸收了一部分 HIbernate 的优点, 提供集成的 CRUD, 基本上现在开发中都使用 Mybatis Plus 替代原生 Mybatis 框架

敲黑板: MybatisPlus 不能和 Mybatis 同时使用

使用流程(三步走)

  1. 添加 Maven 依赖
  2. MyBatisPlus 配置
  3. 编写 3 种文件(可使用插件生成,Idea Mybatis generater)

    • 实体 entity
    • Dao 层接口 Mapper
    • Xml 文件中的 Sql 语句

第一步 添加 Maven 依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatisplus-spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

第二步 在 application.yml 中配置 Mybatis Plus

使用 properties 配置文件的可以在 http://www.toyaml.com/index.html 进行 yml 文件的转换

重点!!!

第一行的 xml 文件扫描, 此处的 xml 文件存放在 resource 下的 mapper 路径下 (我的路径是 resource/mapper/xx 模块 /xxx.xml)
第二行的实体扫描!!! 要根据自己的 entity 目录进行配置 自己根据自己的实体类路径修改 typeAliasesPackage, 或者使用我的这种模块化工程路径(工程根目录 /modules/xx 模块 /entity/xxx.class)

mybatis-plus:
  mapper-locations: classpath:mapper/**/*.xml       #__对应第三步的 mapper 路径__
  #实体扫描,多个 package 用逗号或者分号分隔
  typeAliasesPackage: io.renren.modules.*.entity    #__对应第三步的 entity 路径__
  global-config:
    #主键类型  0:"数据库 ID 自增", 1:"用户输入 ID",2:"全局唯一 ID (数字类型唯一 ID)", 3:"全局唯一 ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新 mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #序列接口实现类配置
    #key-generator: com.baomidou.springboot.xxx
    #逻辑删除配置
    logic-delete-value: -1
    logic-not-delete-value: 0
    #自定义填充策略接口实现
    #meta-object-handler: com.baomidou.springboot.xxx
    #自定义 SQL 注入器
    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    call-setters-on-nulls: true

没添加 mysq 数据源的再添加如下配置

spring:
    datasource:
        continue-on-error: false
        driver-class-name: com.mysql.jdbc.Driver
        username: root                                       ## 根据自己 MySQL 的用户名修改
        url: jdbc:mysql://127.0.0.1:3306/renren_test  ## 根据自己 MySQL 的 ip 和端口修改
        password: root                                       ## 根据自己 MySQL 的密码修改

第三步 进入正题

之前的步骤都是 Mybatis 的配置和管理, 以下才是真正的业务代码
  1. entity

文件放在 entity 目录下(要与第二步的实体扫描路径对应, 忽略的回去仔细看第二步)

@TableName("sword")
public class Sword {
    @TableId
    private Long id;
    private String name;

}

之前用过 JPA 的可能直接运行发现并没有在数据库中建表, 因为 Mybatis 不支持自动根据实体类创建表, 所以需要自己建表, 如果要引入这个功能可以引入 JPA, 只利用 JPA 的自动建表功能, 本文为了简单明了不涉及, 可以查看我另一篇文章 Mybatis 加入 JPA 的自动建表功能

  1. mapper 放在 Dao 目录下
@Repository
@Mapper
public interface SwordMapper {Sword selectSword(Pagination page, String id);
    void insertSword(@Param("name") String name
    );
}
  1. xml(要与第二步的 mapper 扫描路径对应, 忽略的回去仔细看第二步)
<?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="io.renren.modules.test.Dao.SwordMapper">

    <select id="selectSword" resultType="io.renren.modules.test.entity.Sword">
       select * from sword limit 1
    </select>
    <insert id="insertSword">
        insert into sword (name) values (#{name})
    </insert>

</mapper>

Mybatis 框架的文件引入方式:

  • entity 通过第二步的配置 typeAliasesPackage 进行查找, 也可以通过注解方式查找
  • Mybatis 的 xml 与 mapper 对应,mapper 提供 java 层的接口,xml 保存相对应的 sql 语句
  • xml 在第二步的配置中由 Mybatis 发现, 相对应的 Mapper 文件在 xml 中通过 namespace 的方式关联

最后一步 测试

在 Controller 文件中实现 Restful 接口 SwordController.class

@RestController
@RequestMapping
public SwordController {
    @Autowired // 自动注入 mapper
    private SwordMapper swordMapper;
    
    @GetMapping("sword")
    public sword(UserEntity userEntity) {Sword sword1 = new Sword();
        sword1.setName("这是一把剑");
        Sword sword = swordMapper.selectSword("1");
        return sword;
    }
}

访问 127.0.0.1:8080/demo/sword
<div align=”left”>
<img src=”https://user-gold-cdn.xitu.io/2018/8/31/1658db422fb834d1?w=271&h=138&f=png&s=5925″ alt=”” >
</div>

大功告成!

后记

在其他的博客中大家可能看到, 有很多利用 sqlsession 或者 SqlSessionFactoryBean 来加载 Mybatis 配置文件, 我这里又没有 sqlsession, 经常有人会被搞得一头雾水, 这里解释一下, 在原生的 mybatis 中,sqlsession 可以由 SqlSessionFactory 创建; 而在 mybatis-spring 中则需要通过 SqlSessionFactoryBean 来创建,并传入 datasource。
像这样

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
      <property name="configLocation">  
          <value>classpath:mybatis/mapper.xml</value>  
      </property>  
      <property name="dataSource" ref="dataSource" />  
</bean> 

但是在 Springboot 中,mybatis-spring-boot 支持自动创建并注册 SqlSessionFactoryBean,所以 sqlsession 的配置并不需要。感谢 Springboot.

正文完
 0