Search code examples
javamysqldatabasemybatisibatis

Passing database name in mybatis


I need to pass the database name via a parameter in a hashmap.

My Mybatis XML is

<select id="getById" parameterType="hashmap" resultMap="result">
    SELECT * FROM #{db}.CONTACT WHERE CONTACT_NAME = #{name}
</select>

And my Java Call is

hm.put("db","abc");
hm.put("name","def");
Contact c=contactDAO.selectById(hm);

But I get the following error

The error occurred while setting parameters
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your      
SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax    
to   use near ''abc'.CONTACT WHERE CONTACT_NAME = 'def'' at line 1

Can we not pass database name as a parameter in mybatis ?


Solution

  • You need to use ${} instead of #{} for direct String substitution.

    <select id="getById" parameterType="hashmap" resultMap="result">
        SELECT * FROM ${db}.CONTACT WHERE CONTACT_NAME = #{name}
    </select>