本文介绍了MyBatis:使用动态查询比较String值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MyBatis映射一些查询,我需要比较 String 参数( myString )。

I'm using MyBatis to map some queries where I need to compare a String argument (myString).

我的Mapper 界面是:

My Mapper interface is:

公共地图< ;整数,字符串> findSomething(@Param(myString)String myString);

我的 XML 如下:

<select id="findSomething" parameterType="String" resultType="Map">
    SELECT column1 as key,
           column2 as value
    FROM my_table
    <where>
         <choose>
            <when test="myString == 'xxx'">
                column3 = 1
            </when>
            <when test="myString == 'yyy'">
                myColumn  = 2
            </when>
            <when test="myString == 'zzz'">
                myColumn  = 3
            </when>
        </choose>
    </where>
    ORDER BY value;
</select>

当我执行此语句时,抛出以下错误:

When I execute this statement the following error is throwed:

ERROR [stderr] Caused by: org.apache.ibatis.exceptions.PersistenceException:
ERROR [stderr] ### Error querying database.  Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'myString' in 'class java.lang.String'

A 字符串以这种方式进行比较,闻起来很糟糕。不幸的是,它是数据库建模的方式。

A String comparison made this way, smells bad. Unfortunately it was the way database was modeled.

MyBatis版本: 3.2.2

MyBatis version: 3.2.2

推荐答案

当然,我必须经历一个复杂的方法。

Definitely I had to go through a complicated approach.

更改了mapper方法签名:

Changed mapper method signature:

public Map<Integer, String> findSomething(@Param("myPojo") MyPojo myPojo);

XML 必须是:

<select id="findSomething" resultType="Map">
SELECT column1 as key,
       column2 as value
FROM my_table
<where>
     <choose>
        <when test="myPojo == 'xxx'">
            column3 = 1
        </when>
        <when test="myPojo == 'yyy'">
            myColumn  = 2
        </when>
        <when test="myPojo == 'zzz'">
            myColumn  = 3
        </when>
    </choose>
</where>
ORDER BY value;

请不要忘记,作为POJO,参数类必须具有相应的getter和setter。

Just don't forget, being a POJO, the parameter class must have it's respective getters and setters.

这篇关于MyBatis:使用动态查询比较String值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:20
查看更多