Search code examples
javamysqlannotationsmybatisspring-mybatis

How to insert an object(more than 10 properties) into mysql via mybatis based on annotation without list all properties


I want to insert an Object with more than 10 properties into mysql via mybatis based on annotation. But I must list all properties, it's too inconvenient. I want to know is there some ways to insert an object easily without list all properties via mybatis. Here is my snippet. Thanks a lot.

@Insert("insert into poi_shop(name,brand,tags,status,phone,mobile,business_time,address,city,lng,lat,business_type,attribute_json) values(#{name},#{brand},#{tags},#{status},#{phone},#{mobile},#{business_time},#{address},#{city},#{lng},#{lat},#{business_type},#{attribute_json})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
public Long insertPoiInfo(PoiBo poiBo);

Solution

  • It is not possible in MyBatis (at least version 3) out of the box.

    MyBatis has auto mapping when reading data from database but doesn't have option to automatically map fields on insertion.

    The reason for this is that MyBatis is very SQL centric that is you need to write SQL manually. It is possible to have implicit fields in SQL select statement (select * from table) so there is automatic mapping to POJO in this case but it is not possible to have implicit fields in update or insert hence no auto-mapping.

    MyBatis can be extended of cause. For example you can use @InsertProvider/@UpdateProvider with the sql generator that generates sql using reflection to get object fields.