How to create a query at runtime using iBATIS

How do I create a request 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 id is dynamic as it is passed as a parameter. But how do you make the table name dynamic? I want to select from table contact, contact1, contact2 .... but now I will be the table name until runtime.

I know you can create a query at runtime with ibatis 3.0, is it possible to do this with ibatis 2.3.4?

+2


source to share


2 answers


I found that 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);

      

+1


source


Building a complete query with iBatis3 (not just the 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);
}

      

0


source







All Articles