In order to dynamically pass the condition value of where clause in MyBatis, I think that it is common to treat it as a prepared statement using "#" as shown below.
SQL definition file.xml
<select id="getHogeValue" resultType="java.util.Map">
select *
form hoge_table
where foo_1 = #{foovalue}
</select>
This section describes how to dynamically change the column to be acquired. In other words, it is useful when the column specified in the select clause is indefinite.
Java:JDK1.7 MyBatis:mybatis-3.2.5.jar
Instead of passing it as a prepared statement value Use "$" to pass as a string.
Below is an example.
Data access class.java
//Define the dynamic part of the column name in List
List<Integer> columnIdList = Arrays.asList(1,2,3,4);
//Set List of column name dynamic part as Map
Map params = new HashMap();
params.put("column_id_list", columnIdList);
//FOO from Hoge table_1, FOO_2, FOO_3, FOO_4, BAR_1, BAR_2, BAR_3, BAR_Get 4
List<Map> hogeValueLsit = hogeTableMapper.getHogeValue(params);
//Check the acquired contents
for (Map elm : hogeValueLsit) {
int idx = 0;
for (Integer columnId : columnIdList) {
String foo = (String)elm.get("FOO_"+columnId);
System.out.println("FOO_" + idx + "The second is" + foo + "is.");
String bar = (String)elm.get("BAR_"+columnId);
System.out.println("BAR_" + idx + "The second is" + bar + "is.");
}
}
SQL definition file.xml
<select id="getHogeValue" resultType="java.util.Map">
select
<foreach item="column_id" collection="column_id_list">
foo_${column_id}
,bar_${column_id}
</foreach>
from hoge_table
</select>
Note that the column name is "uppercase" when retrieving on the Java side Even if the SQL definition file side uses lowercase "foo_" The Map key on the Java side can only be obtained with "FOO_" in uppercase.
that's all.
Recommended Posts