mybatis第一话 - mybatis,缘分让我们相遇

131 阅读4分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

介绍一下作者orm框架使用的升级之路吧

  • hibernate 全自动化,但复杂的查询时简直要程序员的命
  • ibatis 半自动话,但是存在重复代码和硬编码,不易管理
  • mybatis 半自动化,利用接口的动态代理实现,使用至今

总得来说,技术再不断的进步,框架也封装的越来越完整,简单。

mybatis官网的介绍

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。

1. Springboot 集成Mybatis

1.1 项目架构

在这里插入图片描述

1.2 pom.xml

  • 基于springboot 2.5.6版本,这里只贴一下mybatis依赖
<!--Mysql依赖包-->
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <scope>runtime</scope>
</dependency>
<!--mybatis-->
<dependency>
 <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
 <version>2.2.0</version>
</dependency>

1.3 yml配置文件

server:
  port: 12233
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.0.100:3306/demo_test?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
    username: root
    password: 123456

#mybatis xml资源文件扫描
mybatis:
  mapperLocations: classpath:mapper/**.xml

1.4 数据库表结构

CREATE TABLE `user_info` (
 `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
 `name` VARCHAR(50) NULL DEFAULT NULL,
 `age` INT(11) NULL DEFAULT NULL,
 `crad` VARCHAR(50) NULL DEFAULT NULL,
 `create_time` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
 `update_time` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
)
ENGINE=InnoDB
;

1.5 TestMapper接口

//注解莫忘
@Mapper
public interface TestMapper {
    void insert(Map<String, Object> map);
    int update(Map<String, Object> map);
    List<Map<String, Object>> select(Long id);
    void delete(Long id);
}

1.6 TestMapper.xml sql文件

<?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.example.demo.mapper.TestMapper">
 <insert id="insert" parameterType="Map" useGeneratedKeys="true" keyProperty="id">
        insert into user_info(`name`,`age`,`crad`) values (#{name},#{age},#{crad})
    </insert>
 
 //其他的省略了 后面详细的有贴
</mapper>

1.7 TestMybatisController

  • 直接和注解service一样使用,这里简便代码就没创建service层了
@Resource
TestMapper testMapper;

2. mybatis的insert使用

2.1 单数据插入

  • java代码
@GetMapping("/data/insert")
public Object insert() {
    Map<String, Object> map = new HashMap<>();
    map.put("name", "张三" + new Date().getTime());
    map.put("age", 19);
    map.put("crad", new Date().getTime());
    testMapper.insert(map);
    return map;
}
  • xml代码
<insert id="insert" parameterType="Map" useGeneratedKeys="true" keyProperty="id">
    insert into user_info(`name`,`age`,`crad`) values (#{name},#{age},#{crad})
</insert>
  • 测试结果 {"name":"张三1644995140376","id":1,"crad":1644995140376,"age":19}

从代码中可以得知,是没有赋值id的,但是返回的数据又有id,达到这个效果的在xml代码里面

useGeneratedKeys 是否自动获取生成的主键Id keyProperty 主键id的列名

例如crad是唯一键,这是再插入一条重复crad的数据,希望只是更新该怎么做呢?

  • 插入数据主键唯一,如果存在则更新
<insert id="insert" parameterType="Map" useGeneratedKeys="true" keyProperty="id">
    insert into user_info(`name`,`age`,`crad`) values (#{name},#{age},#{crad})
  //只需要加这行代码就好了 标识如果主键已存在 则更新update_time  = #{updateTime}
    on duplicate key update update_time = #{updateTime}
</insert>

2.2 批量数据插入

  • java代码
@GetMapping("/data/insertAll")
public Object insertAll() {
    List<Map<String, Object>> list = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三" + new Date().getTime());
        map.put("age", 19);
        map.put("crad", i + "_" + new Date().getTime());
        list.add(map);
    }
    //由于xml中配置自动获取生成的主键id 经过断点查看 这里依旧生效
    int i = testMapper.insertAll(list);
    //返回的是插入的数据条数
    return i;
}
  • xml代码
<insert id="insertAll" parameterType="Map" useGeneratedKeys="true" keyProperty="id">
      insert into user_info(`name`,`age`,`crad`) values
      <foreach collection="list" item="item" separator=",">
  (#{item.name},#{item.age},#{item.crad})
   </foreach>
</insert>

这里接触到的是foreach函数了,它总共有五个成员变量

  • collection 数据集合的名称,我外面传的名称就是list,也可以通过@Param(value="xxx")自定义
  • item 集合中的每一个数据
  • separator 每次遍历的分隔符号
  • open 开始遍历时添加的符号
  • close 结束遍历时添加的符号

open和close 会在后面批量查询时贴出来

批量插入过程中主键唯一,则更新

<insert id="insertAll" parameterType="Map" useGeneratedKeys="true" keyProperty="id">
      insert into user_info(`name`,`age`,`crad`) values
      <foreach collection="list" item="item" separator=",">
  (#{item.name},#{item.age},#{item.crad})
   </foreach>
   on duplicate key update name = values(name)
</insert>

有所不同的是取值为values(name)

3. mybatis的update使用

  • java代码
@GetMapping("/data/update")
 public Object update(@RequestParam Long id) {
     Map<String, Object> map = new HashMap<>();
     map.put("id", id);
     map.put("name", "李四" + new Date().getTime());
     map.put("age", 19);
     map.put("crad", new Date().getTime());
     int i = testMapper.update(map);
     //i 返回的是更新的条数
     return i;
 }
  • xml代码
<update id="update" parameterType="Map">
 update user_info
 <set>
  <if test="name != null">
   `name` = #{name},
  </if>
  <if test="age != null">
    `age` = #{age},
  </if>
  <if test="crad != null">
   `crad` = #{crad},
  </if>
 </set>
 where id = #{id}
</update>

update里面的含义标签

  • set 包裹整个需要更新的代码块,会自动去掉最后一个 ,
  • trim suffixOverrides去掉指定前后,前后缀结尾的指定字符

4. mybatis的select使用

  • java代码
@GetMapping("/data/select")
public Object select(@RequestParam(required = false) Long id) {
    Map<String, Object> map = new HashMap<>();
    map.put("age", 19);
    //批量查询用
    map.put("ids", Arrays.asList(1, 2, 3));
    List<Map<String, Object>> mapList = testMapper.select(map);
    return mapList;
}
  • xml代码
<select id="select" parameterType="Map" resultType="Map">
 select * from user_info
 <where>
  <if test="ids != null and ids.size()>0">
   and id in
   <foreach collection="ids" item="id" open="(" close=")" separator=",">
    #{id}
   </foreach>
  </if>
  <choose>
   <when test="age != null">
    and age = #{age}
   </when>
   //age < 18  &lt; <符号的意思 &gt; >符号的意思
   <when test="age &lt; 18">
    and age = 0
   </when>
   <otherwise>
    and age > 18
   </otherwise>
  </choose>
  <if test="id != null">
   and id = #{id}
  </if>
 </where>
</select>

使用标签含义

  • where 条件语句的起点,如果是where and会自动去掉第一个and,也可以直接用where 1=1
  • if 判断标签 test中为判断语句,为真才会走该语句
  • foreach insert有描述,不在细说
  • choose 多条件判断语句 if、elseIf和else的意思

5.mybatis的delete使用

  • java代码就不贴了,直接贴xml,多个条件就用map或者bean
<delete id="delete" parameterType="Long">
    delete from user_info where id = #{id}
 </delete>

重在灵活运用,以上就是本章的全部内容了。

上一篇:Springboot源码分析第三弹 - 自动装配扩展,手动实现一个starter 下一篇:mybatis第二话 - mybatis,多数据源的快乐你懂吗?

敏而好学,不耻下问