Search code examples
ibatis

How to create query at runtime with iBATIS


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);