How to create query at runtime with iBATIS
-
19-09-2019 - |
Question
How can I create a query at runtime using ibatis (Java)? I want the table name to be dynamic. For example I have this xml file:
<resultMap id="result" class="Contact">
<result property="id" column="id"/>
<result property="firstName" column="firstName"/>
<result property="lastName" column="lastName"/>
<result property="email" column="email"/>
</resultMap>
<select id="getById" resultMap="result">
select * from contact where id=#id#
</select>
Here the id is dynamic since it is passed as a parameter. But how can I make the table name dynamic? I want to select from table contact, contact1, contact2.... but i will now the table name until runtime.
I know you can create the query at runtime with ibatis 3.0 is it possible to do it with ibatis 2.3.4?
Solution
I have found you can achieve this.
<select id="getRighe"
remapResults="true"
resultMap="resultRighe"
parameterClass="java.util.Map">
select * from
$tablePrefix$_righe
where IDUser = #IDUser#
</select>
Java code:
param.put("IDUser", IDUser);
param.put("tablePrefix", "NAG");
utente = (Riga)getSqlMapClientTemplate().queryForObject("getRighe", param);
OTHER TIPS
Creating full query with iBatis3 (not only table name):
private void createSelect(String statementId, String sql, Class<?> resultType) {
Configuration ibatisConfig = session.getConfiguration();
SqlSource sqlSource = new SqlSourceBuilder(ibatisConfig).parse(sql, Map.class);
Builder statement = new MappedStatement.Builder(ibatisConfig, statementId, sqlSource, SqlCommandType.SELECT);
List<ResultMapping> resultMapList = new ArrayList<ResultMapping>();
ResultMap resultMap = new ResultMap.Builder(ibatisConfig, statementId, resultType, resultMapList, true).build();
ibatisConfig.addResultMap(resultMap);
List<ResultMap> resultMaps = new ArrayList<ResultMap>();
resultMaps.add(resultMap);
statement.resultMaps(resultMaps);
ibatisConfig.addMappedStatement(statement.build());
}
To execute it:
private List<Object> executeSelect(String sqliteStatementId, Map<String, Object> params) {
return session.selectList(sqliteStatementId, params);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow