SpringBoot Mybatis Insert null Fields

I’m using SpringBoot and MyBatis. When tried to insert/update some rows into a table, I got the fllowing:

The column remark in the table user was setted to NOT NULL, and the value of the column to insert was null. That’s why I received the error.

This is the update method in class UserMapper:

I can fix the error simply by setting an empty string to the field remark in object user. But the same problem exists in some other tables, I have to repeat the operation many times, which seems really ugly.

The best solution is to set default value for all null fields automatically and silently.

PageHelper (the pagination plugin for springboot-mybatis) showed me the way:

  1. add a MyBatis interceptor to obtain the argument instance before executing insert/update operation
  2. set default value for null fields through java reflection

First, let’s define the interceptor:

The key is the annotation @Signature

The annotation specified which class and method to intercept.
The interface org.apache.ibatis.executor.Executordefined all the db operations, including INSERT and UPDATE which are completed by method update.

Second, let’s realise the method of padNullFields:

I used java reflection to set default value for null fields. In my project, I only need to set default value for fields with types of String and LocalDateTime. If you want to add more, please change the method setDefaultValue.

The last work is letting the interceptor work in springboot, all we need to do is to add the interceptor into sqlSessionFactory

After adding all the code into my project and rerunning test case, all the Exceptions disappeared.

End!

Leave a Reply

Your email address will not be published. Required fields are marked *