3

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.

2
  • Use a Map of parameters. Put the table name and the other details into this map Commented Feb 8, 2014 at 20:28
  • Yes, the Map is a working solution too, but principally the same as if I put the table name into the object. The table name and the object properties have to be in the same value object. Commented Feb 9, 2014 at 12:01

1 Answer 1

4

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})
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks 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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.