Question

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.

Was it helpful?

Solution

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})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top