Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About passing table name as a parameter in mybatis

When i try to pass a table name as parameter to the sql mapping, such as

public MatchResult get(long id, String tablename);

Mapper xml:

<select id="get" parameterType="long" resultType="myresult">
    select * from ${1} where id=#{0}
</select>

But it does not work.

like image 909
luckyee Avatar asked Feb 23 '15 02:02

luckyee


1 Answers

${} doesn't support the parameter index according to my test. You can use Param annotation to specify the parameter name in your mapper API declaration.

public MatchResult get(long id, @Param("tablename") String tablename);

Mapper xml:

<select id="get" resultType="myresult">
    select * from ${tabelname} where id=#{0}
</select>

An alternative is to use an object of your own class or a map as the parameter if you don't want the IBatis/MyBatis specific annotation Param in your mapper API declaration.

Take the map as an example, your java API could be:

public MatchResult get(Map<String, Object> params);

The mapper xml statements could be:

<select id="get" parameterType="map" resultType="myresult">
    select * from ${tablename} where id=#{id}
</select>

And put the id and tablename to the map with the key "id" and "tablename", before invoking the API.

like image 160
Landys Avatar answered Oct 03 '22 20:10

Landys