mengying.ye mengying.ye - 4 years ago 104
SQL Question

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);

Answer Source

It is not possible in MyBatis (at least version 3).

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download