0

MyBatis 3.1.1 allows either #{...} for prepared statements params, or ${...} for every-time replacement.

I am missing something what would allow to parametrize parts of the SQL statement but still keep it prepared statement; i.e. replace during configuration.

How can I do that? Maybe using some SQL fragments?

Update:

I found:

<sql id="userColumns"> id,username,password </sql>
<select id="selectUsers" parameterType="int" resultType="hashmap">
    SELECT <include refid="userColumns"/> some_table WHERE id = #{id}
</select>

See http://www.mybatis.org/core/sqlmap-xml.html#sql This would be it if ${...} could be used inside of it.

Community
  • 1
  • 1
Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277

3 Answers3

1

I think I found it...

<sql id="userColumns"> id,username,password </sql>

And then

<select id="selectUsers" parameterType="int" resultType="hashmap">
    SELECT <include refid="userColumns"/>
    FROM some_table
    WHERE id = #{id}
</select>

So I will use ${...} in that and that should get me there.

See http://www.mybatis.org/core/sqlmap-xml.html#sql

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
1

in my project we have a very simple solution for this case.

We have a String called TABLENAME in the Data Objects. When we construct the Objects we initialize the tablename. and in the sqls we have the tablename enquoutet.

in the DataObject:

String TABLENAME;
public String getTABLENAME() {return TABLENAME;}
public void setTABLENAME(String tablename) {this.TABLENAME = TABLENAME;}

in the sqls:

<delete id="simpleDelete" parameterClass="Integer">
    delete from ${jdbc.schema}.$TABLENAME$ 
    WHERE ID = #ID#
</delete>

I don't know if this is the best solution, but it works quite well. I am open for better solutions.

duffy356
  • 3,678
  • 3
  • 32
  • 47
0

Since <sql> doesn't work as needed for this purpose, I filled a feature request. http://code.google.com/p/mybatis/issues/detail?id=627

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277