How to let MyBatis annotation to set the id and timestamp properties of the JavaBean I passed in ?

If you are with a auto-generated key, when you carry out a method like this

	public void saveNewUser(User user);

what do you expect besides a new record in DB?  

You want the user.id also has been set after the execution. That’s what real ORM does

With MyBatis, you can do it like the following. I believe you already know it.


	@Insert("insert into User(UserName, Password) values (#{userName}, #{password}")
	@SelectKey(statement = "select last_insert_id() as id", keyProperty = "id", keyColumn = "Id", before = false, resultType = Long.class)
	public void saveNewUser(User user);

However, the real world is more complicated. In addition to id propety, it also has createTime and updateTime that should be set after execution. What to do? The solution is a little bit dirty.


	@Insert("insert into User(UserName, Password, CreateTime, UpdateTime) values (#{userName}, now(), now())")
	@SelectKey(statement = "select Id,CreateTime,UpdateTime from User where id =  last_insert_id()", keyProperty = "id,createTime,updateTime" , 
keyColumn = "Id,CreateTime,UpdateTime", 
before = false, resultType = java.util.Map.class)
	public void saveNewUser(User user);

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.