Mybatis映射属性到列
我有一个查询映射器,如下所示:Mybatis映射属性到列,mybatis,Mybatis,我有一个查询映射器,如下所示: <select id="searchSomething" parameterType="SomeType" resultType="SomeOtherType"> select xxxxx from T_XXXX where 1=1 <if test="propertyName == 'userName'"> and USER_NAME = #{propertyValue} </if> <i
<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>
一种方法是使用: 准备两个ArrayList,一个带有propertyNames,另一个带有PropertyValue。 确保它们的顺序正确,即propValuesList[i]应该具有propNamesList[i]的值 然后放入HashMap并将其作为输入传递给mapped语句:
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>
然后在映射语句中:
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}的用法。我认为如果在代码中进行参数列转换,并将结果列作为参数传递,效果会更好。在这种情况下,您可以这样做:
<select id="searchSomething" parameterType="SomeType" resultType="SomeOtherType">
select xxxxx
from T_XXXX
where 1=1
and
${propertyColumn} = #{propertyValue}
</select>
当然,您需要将propertyColumn添加到您的VO。这意味着我必须在java代码中保留属性列映射。但这似乎是唯一的办法。非常感谢。