本文介绍了如何在不列出所有属性的情况下基于注解通过mybatis将一个对象(超过10个属性)插入到mysql中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过基于注解的mybatis向mysql中插入一个超过10个属性的Object.但是我必须列出所有属性,太不方便了.我想知道是否有一些方法可以轻松插入对象而无需通过 mybatis 列出所有属性.这是我的片段.非常感谢.

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

推荐答案

在 MyBatis(至少版本 3)中无法开箱即用.

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

MyBatis 在从数据库读取数据时有自动映射,但没有选项在插入时自动映射字段.

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

这样做的原因是 MyBatis 非常以 SQL 为中心,即您需要手动编写 SQL.SQL select 语句(select * from table)中可能有隐式字段,因此在这种情况下会自动映射到 POJO,但在更新或插入中不可能有隐式字段,因此没有自动-映射.

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 可以扩展.例如,您可以将 @InsertProvider/@UpdateProvider 与 sql 生成器一起使用,该生成器使用反射生成 sql 以获取对象字段.

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.

这篇关于如何在不列出所有属性的情况下基于注解通过mybatis将一个对象(超过10个属性)插入到mysql中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:31