经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MyBatis » 查看文章
浅谈Mybatis之参数传递的几种姿势
来源:jb51  时间:2021/9/27 11:06:10  对本文有异议

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

I. 环境配置

我们使用SpringBoot + Mybatis + MySql来搭建实例demo

  • springboot: 2.2.0.RELEASE
  • mysql: 5.7.22

1. 项目配置

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot</groupId>
  4. <artifactId>mybatis-spring-boot-starter</artifactId>
  5. <version>2.2.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>mysql</groupId>
  9. <artifactId>mysql-connector-java</artifactId>
  10. </dependency>
  11. </dependencies>

核心的依赖mybatis-spring-boot-starter,至于版本选择,到mvn仓库中,找最新的

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

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

2. 数据库表

用于测试的数据库

  1. CREATE TABLE `money` (
  2. `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  3. `name` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名',
  4. `money` int(26) NOT NULL DEFAULT '0' COMMENT '钱',
  5. `is_deleted` tinyint(1) NOT NULL DEFAULT '0',
  6. `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  7. `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  8. PRIMARY KEY (`id`),
  9. KEY `name` (`name`)
  10. ) ENGINE=InnoDB AUTO_INCREMENT=551 DEFAULT CHARSET=utf8mb4;

II. 参数传递

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

数据库实体对象

  1. @Data
  2. public class MoneyPo {
  3. private Integer id;
  4.  
  5. private String name;
  6.  
  7. private Long money;
  8.  
  9. private Integer isDeleted;
  10.  
  11. private Timestamp createAt;
  12.  
  13. private Timestamp updateAt;
  14.  
  15. private Integer cnt;
  16. }
  17.  

mapper接口

  1. @Mapper
  2. public interface MoneyMapper {
  3. }

xml文件,在资源文件夹下,目录层级与mapper接口的包路径完全一致(遵循默认的Mapper接口与xml文件绑定关系,详情查看SpringBoot系列Mybatis之Mapper接口与Sql绑定几种姿势

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.git.hui.boot.mybatis.mapper.MoneyMapper">
  4.  
  5. <resultMap id="BaseResultMap" type="com.git.hui.boot.mybatis.entity.MoneyPo">
  6. <id column="id" property="id" jdbcType="INTEGER"/>
  7. <result column="name" property="name" jdbcType="VARCHAR"/>
  8. <result column="money" property="money" jdbcType="INTEGER"/>
  9. <result column="is_deleted" property="isDeleted" jdbcType="TINYINT"/>
  10. <result column="create_at" property="createAt" jdbcType="TIMESTAMP"/>
  11. <result column="update_at" property="updateAt" jdbcType="TIMESTAMP"/>
  12. </resultMap>
  13. <sql id="money_po">
  14. id, name, money, is_deleted, create_at, update_at
  15. </sql>
  16. </mapper>
  17.  

1. @Param注解

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

一个简单的case如下

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

重点关注上面的参数

通过@Param来指定传递给xml时的参数名
对应的xml文件中的sql如下,使用#{}来实现参数绑定

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

2. 单参数

接下来我们看一下不使用@Param注解时,默认场景下,xml中应该如何指定参数;因为单参数与多参数的实际结果不一致,这里分开进行说明

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

mapper接口定义如下

  1. /**
  2. * 单个参数时,默认可以直接通过参数名来表示,实际上#{}中用任意一个值都可以,没有任何限制,都表示的是这个唯一的参数
  3. * @param id
  4. * @return
  5. */
  6. MoneyPo findById(int id);
  7.  
  8. /**
  9. * 演示xml中的 #{} 为一个匹配补上的字符串,也可以正确的实现参数替换
  10. * @param id
  11. * @return
  12. */
  13. MoneyPo findByIdV2(int id);

对应的xml文件内容如下

  1. <select id="findById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
  2. select
  3. <include refid="money_po"/>
  4. from money where id=#{id}
  5. </select>
  6.  
  7. <select id="findByIdV2" parameterType="java.lang.Integer" resultMap="BaseResultMap">
  8. select
  9. <include refid="money_po"/>
  10. from money where id=#{dd}
  11. </select>

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

3. 多参数

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

  • param1…N: 其中n代表的接口中的第几个参数
  • arg0…N
  1. /**
  2. * 不指定参数名时,mybatis自动封装一个 param1 ... paramN的Map,其中n表示第n个参数
  3. * 也可以使用 arg0...n 来指代具体的参数
  4. *
  5. * @param name
  6. * @param money
  7. * @return
  8. */
  9. List<MoneyPo> findByNameAndMoney(String name, Integer money);

对应的xml如下

  1. <select id="findByNameAndMoney" resultMap="BaseResultMap">
  2. select
  3. <include refid="money_po"/>
  4. -- from money where name=#{param1} and money=#{param2}
  5. from money where name=#{arg0} and money=#{arg1}
  6. </select>

注意上面的xml中,两种传参都是可以的,当然不建议使用这种默认的方式来传参,因为非常不直观,对于后续的维护很不优雅

3. Map传参

如果参数类型并不是简单类型,当时Map类型时,在xml文件中的参数,可以直接使用map中对应的key来指代

  1. /**
  2. * 参数类型为map时,直接使用key即可
  3. * @param map
  4. * @return
  5. */
  6. List<MoneyPo> findByMap(Map<String, Object> map);

对应的xml如下

  1. <select id="findByMap" resultMap="BaseResultMap">
  2. select
  3. <include refid="money_po"/>
  4. from money
  5. <trim prefix="WHERE" prefixOverrides="AND | OR">
  6. <if test="id != null">
  7. id = #{id}
  8. </if>
  9. <if test="name != null">
  10. AND name=#{name}
  11. </if>
  12. <if test="money != null">
  13. AND money=#{money}
  14. </if>
  15. </trim>
  16. </select>

4. POJO对象

另外一种常见的case是传参为简单的实体对象,这个时候xml中的参数也可以直接使用对象的fieldName来指代,和map的使用方式差不多

  1. /**
  2. * 参数类型为java对象,同样直接使用field name即可
  3. * @param po
  4. * @return
  5. */
  6. List<MoneyPo> findByPo(MoneyPo po);

对应的xml文件如下

  1. <select id="findByPo" parameterType="com.git.hui.boot.mybatis.entity.MoneyPo" resultMap="BaseResultMap">
  2. select
  3. <include refid="money_po"/>
  4. from money
  5. <trim prefix="WHERE" prefixOverrides="AND | OR">
  6. <if test="id != null">
  7. id = #{id}
  8. </if>
  9. <if test="name != null">
  10. AND name=#{name}
  11. </if>
  12. <if test="money != null">
  13. AND money=#{money}
  14. </if>
  15. </trim>
  16. </select>

5. 简单参数 + Map参数

当参数有多个,其中部分为简单类型,部分为Map,这样的场景下参数如何处理呢?

  • 简单类型遵循上面的规则
  • map参数的传参,使用前缀 + “.” + key的方式

一个实例如下

  1. List<MoneyPo> findByIdOrCondition(@Param("id") int id, @Param("map") Map<String, Object> map);
  2.  
  3. List<MoneyPo> findByIdOrConditionV2(int id, Map<String, Object> map);
  4.  

对应的xml如下

  1. <select id="findByIdOrCondition" resultMap="BaseResultMap">
  2. select <include refid="money_po"/> from money where id = #{id} or `name`=#{map.name}
  3. </select>
  4.  
  5. <select id="findByIdOrConditionV2" resultMap="BaseResultMap">
  6. select <include refid="money_po"/> from money where id = #{param1} or `name`=#{param2.name}
  7. </select>
  8.  

6.小结

本文主要介绍mybatis中传参的几种姿势:

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

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

项目

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

到此这篇关于浅谈Mybatis之参数传递的几种姿势的文章就介绍到这了,更多相关Mybatis 参数传递 内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号