2

我有一个查询映射器,如下所示:

<select id="searchSomething" parameterType="SomeType" resultType="SomeOtherType">
  select xxxxx
  from T_XXXX
  where 1=1
  <if test="propertyName == 'userName'">
    and USER_NAME = #{propertyValue}
  </if>
  <if test="propertyName == 'address'">
    and ADDRESS = #{propertyValue}
  </if>
  <if test="propertyName == 'taskDate'">
    and TASK_DATE = #{propertyValue}
  </if>
  <if test="propertyName == 'phone1'">
    and PHONE_1 = #{propertyValue}
  </if>
  <if test="propertyName == 'phone2'">
    and PHONE_2 = #{propertyValue}
  </if>
  ...
</select>

有这么多的属性。我怎样才能简单地将属性名称映射到列名称,如下所示:

<select id="searchSomething" parameterType="SomeType" resultType="SomeOtherType">
  select xxxxx
  from T_XXXX
  where 1=1
    and 
    <propertyToColumn property="propertyName" />
      = #{propertyValue}
</select>

MyBatis 中有类似“propertyToColumn”的东西吗?

我在 iBatis 中找到了“insertColumnName”,它是从 MyBatis 中删除的吗?

parameterType 是一个 java 类,如:

public class SomeType{
  private String propertyName;
  private String propertyValue;
  ... getters and setters
}
4

2 回答 2

2

一种方法是使用:

准备两个 ArrayList,一个带有 propertyNames,另一个带有 propertyValues。确保它们的顺序正确,即propValuesList[i] 应该具有propNamesList[i] 的值。

然后将其放入 HashMap 并将其作为输入传递给映射语句:

Map<String,Object> map = new HashMap<String,Object>();
List<String> propNamesList = new ArrayList<String>();
List<String> propValuesList = new ArrayList<String>();
propNamesList.add(0, "USER_NAME");
propNamesList.add(1, "ADDRESS");

propValuesList.add(0, "admin");
propValuesList.add(1, "hyderabad");

map.put("propNames",propNamesList);
map.put("propValues",propValuesList);

然后在映射语句中:

<select id="selectUsers" parameterType="hashmap" resultMap="UserResult">
    select * from users
    where 1 =1
    <if test="propNames != null and propValues != null">
       <foreach item="propName" index="index" collection="propNames">
        and #{propName} = #{propValues[${index}]}
       </foreach>
    </if>
 </select>

注意使用${index}而不是#{index}

于 2013-01-28T05:40:17.027 回答
1

我认为如果您在代码中进行“参数列”转换,并将结果列作为参数传递,可能会更好。在这种情况下,您可以执行以下操作:

<select id="searchSomething" parameterType="SomeType" resultType="SomeOtherType">
  select xxxxx
  from T_XXXX
  where 1=1
    and 
   ${propertyColumn} = #{propertyValue}
</select>

当然,您需要将propertyColumn添加到您的 VO。

于 2013-01-28T12:56:32.037 回答