Mybatis (ParameterType) 如何传递多个不同类型的参数

107 篇文章 1 订阅

在一些场景下,传参是需要多个参数的。一个参数不太够用,如:parameterType="ImGroup"

最开始的想法是封装一个专用用来当参数的对象,把多个对象包装到一起,这样就要以实现多个参数的传递。但是总感觉这样的方法太笨了,而且封装的对象有可能只能在参数这块用一下,重用性不高。还会导致项目中多一个类文件。

那么应该还可以使用map或者list封装对象。但是毕竟集合的可变性比较高,使用起来又没有类方便。

比起这些思路,我感觉注解的方式最方便。

基于注解

 public List<ImGroup> selectImGroupListByUserId(@Param("userId")String userId, @Param("group") ImGroup imGroup);

去掉parameterType属性。
这里ImGroup 是一个对象,里面有一堆属性,比如:name

<select id="getXXXBeanList" resultType="XXBean">
  select t.* from tableName where id = #{userId} and name = #{group.name}  
</select>  

由于是多参数那么就不能使用parameterType, 这里用@Param来指定哪一个

我的实际代码如下 :
ImGroupMapper.java

   /**
     * 通过UserId来查询
     * @param imGroup
     * @return
     */
    public List<ImGroup> selectImGroupListByUserId(@Param("userId")String userId, @Param("group") ImGroup imGroup);

ImGroupMapper.xml

 <select id="selectImGroupListByUserId" resultMap="ImGroupResult">
        select g.* from im_group_user gu left join im_group g on gu.group_id=g.group_id
        <where>
            gu.user_id=#{userId}
            <if test="group.userCount != null "> and g.user_count = #{group.userCount}</if>
            <if test="group.groupName != null  and group.groupName != ''"> and g.group_name like concat('%', #{group.groupName}, '%')</if>
            <if test="group.groupIntroduction != null  and group.groupIntroduction != ''"> and g.group_introduction = #{group.groupIntroduction}</if>
            <if test="group.groupPortrait != null  and group.groupPortrait != ''"> and g.group_portrait = #{group.groupPortrait}</if>
            <if test="group.groupOwner != null  and group.groupOwner != ''"> and g.group_owner = #{group.groupOwner}</if>
            <if test="group.groupManager != null  and group.groupManager != ''"> and g.group_manager = #{group.groupManager}</if>
        </where>
    </select>

参考

https://developer.aliyun.com/article/650235

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值