MyBatis在表名作为参数时遇到的问题

之前在用MyBatis的时候没用过表名作为参数,最近使用到了。

基于注释使用MyBatis的Dao层代码如下:

@Repository
public interface Base1102Dao {
    @Select(value = "Select * from ${table_name} order by id")
    @ResultType(HashMap.class)
    List<HashMap> getAll(@Param("table_name") String tableName);
}

区别为:在用表作为参数使用的时候不在使用#{param},而是使用${param}。

同时遇到的一个问题是因为在参数的时候没有使用@Parem注解会导致编译器误以为String为一个class,报如下错

// 第二个标红的代码(@Param("table_name"))如果去掉就会报这个错

There is no getter for property named 'table_name' in 'class java.lang.String'

解决方案:加上@Param然后指定一个名字,在sql中使用就可以了

我之前经常不对单个String作为参数的函数用@Param参数注释,因为直接在sql 中写   #{string} 就可以了。但这个不知道为什么一定要这样写(因为参数去当表名了?)。不深究

一篇对@Param参数注解细讲的文章连接:

http://iyiguo.net/blog/2012/09/27/mybatis-param-mapping-rules/

原文地址:https://www.cnblogs.com/Jacck/p/8289300.html