ibatis的select标签有个属性remapResults,该属性默认值为false。在这种查询结果列不确定(或是动态变化)的情况下,为保证查询结果的正确就需要设置remapResults="true",或者当查询结果只是一个动态变化的列时可用 select $selectresultfield$ as resultfield 的形式来解决。
当设置remapResults为"true"时:
iBATIS会在每次查询的时候内省查询结果来设置元数据,来保证返回恰当的结果。这个属性会造成一定的性能损失,所以要谨慎使用,只在你需要的时候使用——查询列发生变化,直接的,或者隐含的,检索的表发生变化。
示例代码:
public class Test {
public String name;
public Timestamp date;
public int id;
}public class TestInsert {
// logger class you can replace it to System.out.println
static Log logger = LogFactory.getLog(TestInsert.class);
public static void main(String[] args) {
// try the dynamic table dealation
HashMap<String, Object> map = new HashMap<String, Object>();
// set the query value
map.put("ID", "dizhuang");
// set the col1 to be selected
map.put("col1", "*");
// set the table name
map.put("tablePrefix", "testsocevent");
// set the col name which you use
map.put("col2", "NAME");
try {
// why args is error?
Test test = (Test) EntityManager.getSqlMapper().queryForObject("getTest", map);
logger.info("id : " + test.id);
logger.info("time :" + test.date);
logger.info("name : " + test.name);
} catch (SQLException e) {
logger.error(e.getMessage(), e);
// e.printStackTrace();
}
}
<select id="getTest" parameterClass="java.util.HashMap"
resultClass="com.neusoft.soc.eventcenter.test.Test"
remapResults="true">
SELECT $col1$
FROM $tablePrefix$
WHERE $col2$ = #ID#
</select>
转载请注明:观测者 » ibatis动态传入表名和列名