我即将使用 myBatis 创建一个动态 SQL 插入,其中表名和保存参数的对象是不同的。像这样:
INSERT INTO ${tablename} (column1, column2) VALUES (#{column1}, #{column2})
接口方法是这样的:
@Insert(CREATE)
@Options(useGeneratedKeys = true, keyProperty = "id", flushCache = true)
public int write(String tablename, Object object) throws Exception;
对象保存字段值的位置:
class Object {
int id;
String column1;
String column2;
getters, setters...
}
不幸的是,我找不到如何做到这一点,我发现的最好的和有效的方法是当表名是对象的属性时,所以 myBatis 可以通过这种方式读取值。出于某种实际原因,我想避免这种方法,也许有人有更好的主意?谢谢。
像
这样使用@Param
注释
@Insert(CREATE)
@Options(useGeneratedKeys = true, keyProperty = "object.id", flushCache = true)
public int write(@Param("tablename") String tablename,
@Param("object") Object object) throws Exception;
和查询
INSERT INTO ${tablename} (column1, column2) VALUES (#{object.column1}, #{object.column2})