m0_72092343 2024-08-27 22:30 采纳率: 50%
浏览 6

mybatis:xml映射器动态sql

问:明明我输入的是Integer类型,为什么结果是编译器认为我输入的是String类型(Parameters: (String))

------------------HeroMapper.xml代码------------------

<!--配置public void getHeroById(@Param(value="id") Integer id);-->
<select id="getHeroById" parameterType="Integer" resultMap="HeroMap">
    select * from `hero`
    <where>
        <if test="id != null and id != ''">
            and `id` = #{id}
        </if>
        <if test="id = null or id = ''">
            and 1=1
        </if>
    </where>
</select>

-----------------测试代码-------------------

@Test
public void getHeroById(){
    List<Hero> heroById = heroMapper.getHeroById(1);
    for (Hero hero : heroById) {
        System.out.println(hero);
    }
    if(sqlSession != null){
        sqlSession.close();
    }
}

测试代码时,我传入一个int类型的参数1,
预期结果为:
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6a79c292]
==> Preparing: select * from hero WHERE id = ?
==> Parameters: 1(Integer)
<== Total: 1
实际结果为:
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6a79c292]
==> Preparing: select * from hero WHERE id = ? and 1=1
==> Parameters: (String)
<== Total: 0

解决方法:删除了第二个标签
HeroMapper.xml代码

<!--配置public void getHeroById(@Param(value="id") Integer id);-->
<select id="getHeroById" parameterType="Integer" resultMap="HeroMap">
    select * from `hero`
    <where>
        <if test="id != null and id != ''">
            and `id` = #{id}
        </if>
    </where>
</select>

测试后,预期结果与实际结果一致

原因未知

  • 写回答

2条回答 默认 最新

  • 吃不了席 2024-08-27 22:31
    关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    这个问题的原因是在<if>标签中的条件判断语句中,你使用了字符串类型的空值('')来判断整数类型的变量。这导致了MyBatis在解析动态SQL时,将参数类型误认为是String类型。

    解决方法:将条件判断语句中的字符串类型的空值('')改为整数类型的空值(0),如下所示:

    <!--配置public void getHeroById(@Param(value="id") Integer id);-->
    <select id="getHeroById" parameterType="Integer" resultMap="HeroMap">
        select * from `hero`
        <where>
            <if test="id != null and id != 0">
                and `id` = #{id}
            </if>
            <if test="id = null or id = 0">
                and 1=1
            </if>
        </where>
    </select>
    

    这样修改后,MyBatis会正确地将参数类型识别为Integer类型,预期结果与实际结果就会一致了。

    评论

报告相同问题?

问题事件

  • 创建了问题 8月27日