2012-10-23 112 views
2

我有一個查詢映射器類似如下: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> 
    <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中刪除?

參數類型是一個Java類,如:

這樣的
public class SomeType{ 
    private String propertyName; 
    private String propertyValue; 
    ... getters and setters 
} 

回答

1

我認爲如果您在代碼中執行「參數列」轉換並將結果列作爲參數傳遞,可能會更好。在這種情況下,你可以做這樣的事情:

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

當然,你需要將propertyColumn添加到您的VO。

+0

我按照你所說的解決了它。謝謝。 – John

2

一種方式是通過使用:

準備兩個的ArrayList,一個與propertyNames,另一個propertValues。 確保它們的順序正確,即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}

+0

這意味着我必須在java代碼中保留屬性 - 列映射。但似乎這是唯一的方法。謝謝。 – John