springboot 整合 mybatis 通用 mapper

一、springboot 整合 mybatis

1. maven 导入依赖

  1. mysql-connector-java。Java程序连接数据源的依赖。
  2. mybatis。原生依赖。
  3. mybatis-spring。会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
  4. mybatis-spring-boot-starter。帮你配置了很多东西到springboot…
    1. 自动检测现有的 DataSource
    2. 创建和注册传递的实例,该实例作为使用 SqlSessionFactoryDataSourceSqlSessionFactoryBean时的输入
    3. 将创建和注册一个实例的SqlSessionTemplate``SqlSessionFactory
    4. 自动扫描映射器,将它们链接并注册到 Spring 上下文,以便它们可以注入您的 beanSqlSessionTemplate
  5. lombok。方便 pojo 类的构建。
<!-- MySQL数据库驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis spring boot启动库 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- mybatis原生库 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
<!-- mybatis spring库-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- @Data注释的依赖-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

错误一: 缺少 mybatis-spring 库,An attempt was made to call a method that does not exist. The attempt was made from the following location:…

错误二: 缺少 3.4+ 版本的mybatis库,@mapper 注释用不了

错误三: 缺少 mybatis-spring-boot-starter,找不到 xxxDao

2. appication.yml 配置

# 数据源配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver # jdbc驱动
    url: jdbc:mysql://xxx.xx.xxx.xxx:xxxx/databaseName?serverTimezone=UTC # 数据库url,格式:jdbc:mysql://ip:端口/数据库名?其他参数(一般要加上时域,不然连不上)
    username: root # 用户名
    password: xxxxx # 密码
# mybatis 配置
mybatis:
  mapper-locations: mapper/*.xml # xml类型的mapper文件所在路径,这里前面省略了classpath:/,可以省略的

3. entity 创建

新建建一个 entity 包,用来放 entity 类。

package com.xxx.xxx.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data // 可以免写setter和getter方法,需要导库lombok
@AllArgsConstructor // 全参构造方法
@NoArgsConstructor // 无参构造方法
@Builder // 链式setter
public class OwnerUnit {
    private long unitId;
    private String unitName;
    private String unitCode;
}

4. Dao 创建

新建一个 dao 包,用来放 mapper 接口。

package com.xxx.xxx.dao;

import com.xxx.xxx.entity.OwnerUnit;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper // 很重要一定要写,注册为mapper。这里也可以不写,但是得在Application上用@MapperScan("dao的包名")
public interface OwnerUnitDao {
    // 方式一:通过注解 @Select、@Delete、@Insert 和 @Update 来CRUD
    @Select("select * from owner_unit where unitName = #{unitName}")
    OwnerUnit getByUnitName(@Param("unitName") String unitName);
    // 方式二:通过xml文件来实现
    void insert(OwnerUnit ownerUnit);
}

在 resources 新建 mapper 文件夹来放 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="com.xxx.xxx.dao.OwnerUnitDao">
    <resultMap id="BaseResultMap" type="com.xxx.xxx.entity.OwnerUnit">
        <result column="unitId" property="unitId" jdbcType="DECIMAL"/>
        <result column="unitName" property="unitName" jdbcType="CHAR"/>
        <result column="unitCode" property="unitCode" jdbcType="CHAR"/>
    </resultMap>

    <sql id="allInfo">
        unitId,
        unitName,
        unitCode
    </sql>

    <insert id="insert">
        INSERT
        INTO owner_unit
        (
        <include refid="allInfo"/>
        )
        VALUES
        (
        #{unitId},
        #{unitName},
        #{unitCode}
        )
    </insert>
</mapper>

须知:

一、Mapper 操作数据库有两种方式

方式一:通过注解 @Select、@Delete、@Insert 和 @update 来CRUD。参考 MyBatis手把手跟我做(八) Mybatis注解 - Mr.Yan (yanhongzhi.com)

方式二:通过xml文件来实现。

二、Dao 和 Mapper 的辨析

这里的 Dao 是 数据访问对象 的意思,从字面理解就是用来访问数据库对象的。而 Mapper 是 映射 的意思,是 ORM 中的M。两者之间其实指的同一个东西,不同人、不同地方有不同的习惯叫法,反正它就是指 用来访问数据库的哪个东西

三、xml 类型 Mapper 的解释

  1. <mapper namespace="com.xxx.xxx.dao.OwnerUnitDao"></mapper>包裹,namescpace给出对应的 dao。
  2. <insert id="insert"></insert>包裹 sql 语句,id给出 dao 中对应的方法。
  3. resultMap确定“特定字段”的返回值类型,resultType确定其他类型的返回值类型,parameterType确定“特定字段”的输入参数类型,“特定字段”:需要哪些字段就封装映射哪些字段。参考 Mapper.xml详解_霓虹深处-CSDN博客

5. 测试

package com.xxx.xxx.controller;

import com.xxx.xxx.dao.OwnerUnitDao;
import com.n303b.gsb.dto.*;
import com.n303b.gsb.service.OwnerUnitService;
import com.n303b.gsb.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("ownerUnit")
public class OwnerUnitController {

    @Autowired
    OwnerUnitDao ownerUnitDao;

    @GetMapping("test1")
    public String test1() {
        return ownerUnitDao.getByUnitName("dd").toString;
    }
    @GetMapping("test2")
    public String test2() {
        OwnerUnit ownerUnit = new OwnerUnit(123, "小卖部", "524369");
        return ownerUnitDao.insert(ownerUnit).toString;
    }
}

二、springboot 整合通用 mapper

1. maven 导入依赖

<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>

提示:看着名字就知道跟mybatis-spring-boot-starter同一类东西

2. appication.yml 改造

# 数据源配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver # jdbc驱动
    url: jdbc:mysql://xxx.xx.xxx.xxx:xxxx/databaseName?serverTimezone=UTC # 数据库url,格式:jdbc:mysql://ip:端口/数据库名?其他参数(一般要加上时域,不然连不上)
    username: root # 用户名
    password: xxxxx # 密码
# mybatis 配置
mybatis:
  type-aliases-package: com.n303b.gsb.entity # entity所在包
# 通用 mapper 配置
mapper: 
  mappers: com.n303b.gsb.baseDao.IBaseDao # 定位 基mapper
  identity: MYSQL

3. entity 改造

通用 mapper 的最大便捷之处在于对数据表单表操作的时,可以不用自己去实现操作数据库的 sql 语句!,而前面基础版本的 mybatis,两种操作数据库的方式都需要写 sql 语句,这就是要用集成通用 mapper 的原因。

不用写 sql 语句,当然得使用 jpa 规范了,故 entity 得映射好数据表,属性得映射好数据表的对应字段。具体做法是使用 @Table@Id@Column等注解来关联映射。

package com.xxx.xxx.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name = "owner_unit") // 对应数据表名
public class OwnerUnit {
    @Id
    @Colunm(name = "unitId")
    private long unitId;
    @Column(name = "unitName")
    private String unitName;
    @Column(name = "unitCode")
    private String unitCode;
}

4. Dao 改造

  • baseDao 包用来放 基 mapper
package com.xxx.xxx.baseDao;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface IBaseDao<T> extends Mapper<T>, MySqlMapper<T> {
}
  • 普通 mapper 去掉 @mapper注解,在 Application 上用@MapperScan("dao的包名")来注册mapper。
package com.xxx.xxx.dao;

import com.xxx.xxx.entity.OwnerUnit;
import org.apache.ibatis.annotations.Param;

public interface OwnerUnitDao {
    // 还是可以:通过注解 @Select、@Delete、@Insert 和 @Update 来CRUD
    @Select("select * from owner_unit where unitName = #{unitName}")
    OwnerUnit getByUnitName(@Param("unitName") String unitName);
    // 还是可以:通过xml文件来实现,但这个插入是单表操作,所以直接用 通用mapper 就好
    // void insert(OwnerUnit ownerUnit);
}
package com.xxx.xxx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan(basePackages = "com.xxx.xxx.dao") // @MapperScan("dao的包名") 来扫描注册mapper
public class GsbApplication {

    public static void main(String[] args) {
        SpringApplication.run(GsbApplication.class, args);
    }

}

5. 测试

同基本mybatis的测试,只需将 dao 中的 insert 方法注释掉即可,这样就可以用到通用mapper的 insert 方法

package com.xxx.xxx.controller;

import com.xxx.xxx.dao.OwnerUnitDao;
import com.n303b.gsb.dto.*;
import com.n303b.gsb.service.OwnerUnitService;
import com.n303b.gsb.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("ownerUnit")
public class OwnerUnitController {

    @Autowired
    OwnerUnitDao ownerUnitDao;

    @GetMapping("test1")
    public String test1() {
        return ownerUnitDao.getByUnitName("dd").toString;
    }
    @GetMapping("test2")
    public String test2() {
        OwnerUnit ownerUnit = new OwnerUnit(123, "小卖部", "524369");
        return ownerUnitDao.insert(ownerUnit).toString; // 这里的 insert 已经是调用了通用 Mapper 的 insert 方法了
    }
}

三、其他

1. 去除警告

  1. 整合通用mapper 清除 No MyBatis mapper was found in 警告_gzt19881123的专栏-CSDN博客
  2. 通用 Mapper 警告信息: <[EntityColumn{table=worker_node, property=‘id’, column=‘ID’,…。entity 用封装类型,别用 int、long这种。

2. 学习资料

  1. 通用 mapper 使用手册,参考 Mybatis通用Mapper介绍与使用_dwf_android的博客-CSDN博客_mybatis通用mapper
  2. 待更新。。。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值