Using myBatis with dynamic table name and object
11,198
Use @Param
annotation like this
@Insert(CREATE)
@Options(useGeneratedKeys = true, keyProperty = "object.id", flushCache = true)
public int write(@Param("tablename") String tablename,
@Param("object") Object object) throws Exception;
and query
INSERT INTO ${tablename} (column1, column2) VALUES (#{object.column1}, #{object.column2})
Author by
derək
Updated on June 07, 2022Comments
-
derək almost 2 years
I'm about to create a dynamic SQL insert using myBatis, where the table name and the object holding the parameters are different. Something like this:
INSERT INTO ${tablename} (column1, column2) VALUES (#{column1}, #{column2})
The interface method would be this:
@Insert(CREATE) @Options(useGeneratedKeys = true, keyProperty = "id", flushCache = true) public int write(String tablename, Object object) throws Exception;
Where the Object holds the field values:
class Object { int id; String column1; String column2; getters, setters... }
Unfortunately I can't find out how to do this, the best and working way I found is when the table name is a property of the Object, so the myBatis can read the value in this way. For some practical reason I'd like to avoid this approach, maybe someone has a better idea? Thanks.
-
derək about 10 yearsThanks for the answer, I did not know it can be identified the object and its property in the query. And of course it worked at the keyProperty = "object.id".