SpringBoot 系列 Mybatis 之参数传递的几种姿态

在 mybatis 的日常开发中,mapper 接口中定义的参数如何与 xml 中的参数进行映射呢?除了咱们罕用的@Param注解之外,其余的形式是怎么的呢?

  • 不增加注解默认场景会怎么?
  • 接口参数类型为Map/POJO又该如何解决?

本文将次要介绍一下mybatis的日常开发中,mapper接口中的定义的参数与xml中占位符的几种映射绑定形式

<!-- more -->

I. 环境配置

咱们应用 SpringBoot + Mybatis + MySql 来搭建实例 demo

  • springboot: 2.2.0.RELEASE
  • mysql: 5.7.22

1. 我的项目配置

<dependencies>    <dependency>        <groupId>org.mybatis.spring.boot</groupId>        <artifactId>mybatis-spring-boot-starter</artifactId>        <version>2.2.0</version>    </dependency>    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>    </dependency></dependencies>

外围的依赖mybatis-spring-boot-starter,至于版本抉择,到 mvn 仓库中,找最新的

另外一个不可获取的就是 db 配置信息,appliaction.yml

spring:  datasource:    url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai    username: root    password:

2. 数据库表

用于测试的数据库

CREATE TABLE `money` (  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,  `name` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名',  `money` int(26) NOT NULL DEFAULT '0' COMMENT '钱',  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创立工夫',  `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新工夫',  PRIMARY KEY (`id`),  KEY `name` (`name`)) ENGINE=InnoDB AUTO_INCREMENT=551 DEFAULT CHARSET=utf8mb4;

II. 参数传递

接下来咱们看一下 Mapper 接口中的参数与 xml 文件中的参数映射的几种姿态;对于 mybatis 我的项目的搭建,这里就略过,重点信息有上面几个

数据库实体对象

@Datapublic class MoneyPo {    private Integer id;    private String name;    private Long money;    private Integer isDeleted;    private Timestamp createAt;    private Timestamp updateAt;    private Integer cnt;}

mapper 接口

@Mapperpublic interface MoneyMapper {}

xml 文件,在资源文件夹下,目录层级与 mapper 接口的包门路完全一致(遵循默认的 Mapper 接口与 xml 文件绑定关系,详情查看SpringBoot 系列 Mybatis 之 Mapper 接口与 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.git.hui.boot.mybatis.mapper.MoneyMapper">    <resultMap id="BaseResultMap" type="com.git.hui.boot.mybatis.entity.MoneyPo">        <id column="id" property="id" jdbcType="INTEGER"/>        <result column="name" property="name" jdbcType="VARCHAR"/>        <result column="money" property="money" jdbcType="INTEGER"/>        <result column="is_deleted" property="isDeleted" jdbcType="TINYINT"/>        <result column="create_at" property="createAt" jdbcType="TIMESTAMP"/>        <result column="update_at" property="updateAt" jdbcType="TIMESTAMP"/>    </resultMap>    <sql id="money_po">      id, name, money, is_deleted, create_at, update_at    </sql></mapper>

1. @Param 注解

在接口的参数上增加@Param注解,在外部指定传递给 xml 的参数名

一个简略的 case 如下

int addMoney(@Param("id") int id, @Param("money") int money);

重点关注下面的参数

  • 通过@Param来指定传递给 xml 时的参数名

对应的 xml 文件中的 sql 如下,应用#{}来实现参数绑定

<update id="addMoney" parameterType="java.util.Map">    update money set money=money+#{money} where id=#{id}</update>

2. 单参数

接下来咱们看一下不应用@Param注解时,默认场景下,xml 中应该如何指定参数;因为单参数与多参数的理论后果不统一,这里离开进行阐明

单参数场景下,xml 中的参数名,能够用任意值来表明

mapper 接口定义如下

/** * 单个参数时,默认能够间接通过参数名来示意,实际上#{}中用任意一个值都能够,没有任何限度,都示意的是这个惟一的参数 * @param id * @return */MoneyPo findById(int id);/** * 演示xml中的 #{} 为一个匹配补上的字符串,也能够正确的实现参数替换 * @param id * @return */MoneyPo findByIdV2(int id);

对应的 xml 文件内容如下

<select id="findById" parameterType="java.lang.Integer" resultMap="BaseResultMap">    select    <include refid="money_po"/>    from money where id=#{id}</select><select id="findByIdV2" parameterType="java.lang.Integer" resultMap="BaseResultMap">    select    <include refid="money_po"/>    from money where id=#{dd}</select>

重点看一下下面的findByIdV2,下面的 sql 中传参应用的是 #{dd},和 mapper 接口中的参数名并不相同,然而最终的后果却没有什么区别

3. 多参数

当参数个数超过 1 个的时候,#{}中的参数,有两种形式

  • param1...N: 其中 n 代表的接口中的第几个参数
  • arg0...N
/** * 不指定参数名时,mybatis主动封装一个  param1 ... paramN的Map,其中n示意第n个参数 * 也能够应用 arg0...n 来指代具体的参数 * * @param name * @param money * @return */List<MoneyPo> findByNameAndMoney(String name, Integer money);

对应的 xml 如下

<select id="findByNameAndMoney" resultMap="BaseResultMap">    select    <include refid="money_po"/>    -- from money where name=#{param1} and money=#{param2}    from money where name=#{arg0} and money=#{arg1}</select>

留神下面的 xml 中,两种传参都是能够的,当然不倡议应用这种默认的形式来传参,因为十分不直观,对于后续的保护很不优雅

3. Map 传参

如果参数类型并不是简略类型,过后 Map 类型时,在 xml 文件中的参数,能够间接应用 map 中对应的 key 来指代

/** * 参数类型为map时,间接应用key即可 * @param map * @return */List<MoneyPo> findByMap(Map<String, Object> map);

对应的 xml 如下

<select id="findByMap" resultMap="BaseResultMap">    select    <include refid="money_po"/>    from money    <trim prefix="WHERE" prefixOverrides="AND | OR">        <if test="id != null">            id = #{id}        </if>        <if test="name != null">            AND name=#{name}        </if>        <if test="money != null">            AND money=#{money}        </if>    </trim></select>

4. POJO 对象

另外一种常见的 case 是传参为简略的实体对象,这个时候 xml 中的参数也能够间接应用对象的 fieldName 来指代,和 map 的应用形式差不多

/** * 参数类型为java对象,同样间接应用field name即可 * @param po * @return */List<MoneyPo> findByPo(MoneyPo po);

对应的 xml 文件如下

<select id="findByPo" parameterType="com.git.hui.boot.mybatis.entity.MoneyPo" resultMap="BaseResultMap">    select    <include refid="money_po"/>    from money    <trim prefix="WHERE" prefixOverrides="AND | OR">        <if test="id != null">            id = #{id}        </if>        <if test="name != null">            AND name=#{name}        </if>        <if test="money != null">            AND money=#{money}        </if>    </trim></select>

5. 简略参数 + Map 参数

当参数有多个,其中局部为简略类型,局部为 Map,这样的场景下参数如何解决呢?

  • 简略类型遵循下面的规定
  • map 参数的传参,应用前缀 + "." + key 的形式

一个实例如下

List<MoneyPo> findByIdOrCondition(@Param("id") int id, @Param("map") Map<String, Object> map);List<MoneyPo> findByIdOrConditionV2(int id, Map<String, Object> map);

对应的 xml 如下

<select id="findByIdOrCondition" resultMap="BaseResultMap">    select <include refid="money_po"/> from money where id = #{id} or  `name`=#{map.name}</select><select id="findByIdOrConditionV2" resultMap="BaseResultMap">    select <include refid="money_po"/> from money where id = #{param1} or `name`=#{param2.name}</select>

6.小结

本文次要介绍 mybatis 中传参的几种姿态:

  • 默认场景下,单参数时,xml 文件中能够用任意名称代替传参
  • 默认场景下,多参数时,第一个参数可用 param1 或 arg0 来示意,第二个参数为 param2 或 arg1。。。
  • 单参数,且为 map 时,能够间接应用 map 的 key 作为传参
  • 单参数,pojo 对象时,应用对象的 fieldName 来示意传参
  • @Param 注解中定义的值,示意这个参数与 xml 中的占位映射关联
  • 多参数场景下,简略对象 + map/pojo 时,对于 map/pojo 中的参数占位,能够通过 paramN.xxx 的形式来实现

最初一个问题来了,mybatis是如何将mapper接口中参数与xml中的占位进行关联映射的呢?

预知后事如何,且看下文详述;我是一灰灰,欢送各位大佬关注回访

III. 不能错过的源码和相干知识点

0. 我的项目

  • 工程:https://github.com/liuyueyi/spring-boot-demo
  • 源码:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/103-mybatis-xml

系列博文

  • 【DB 系列】Mybatis 系列教程之 CURD 根本应用姿态
  • 【DB 系列】Mybatis 系列教程之 CURD 根本应用姿态-注解篇

1. 微信公众号: 一灰灰 Blog

尽信书则不如,以上内容,纯属一家之言,因集体能力无限,不免有疏漏和谬误之处,如发现 bug 或者有更好的倡议,欢送批评指正,不吝感谢

上面一灰灰的集体博客,记录所有学习和工作中的博文,欢送大家前去逛逛

  • 一灰灰 Blog 集体博客 https://blog.hhui.top
  • 一灰灰 Blog-Spring 专题博客 http://spring.hhui.top