简体   繁体   English

如何使用MyBatis迭代对象的所有字段?

[英]How to use MyBatis to iterate all fields of an object?

I want to insert all fields of a object to a row, but I don't know the exact filed names. 我想将对象的所有字段插入一行,但是我不知道确切的文件名。 Does MyBatis support this? MyBatis支持吗?

Mybatis uses OGNL in places where expression is expected including collection attribute of the foreach . Mybatis在期望表达的地方(包括foreach collection属性)使用OGNL

OGNL allows to invoke static methods so you can leverage this. OGNL 允许调用静态方法,因此您可以利用它。

With default scripting engine (assuming that properties names match column names) you can do something like this to generate the list of fields: 使用默认脚本引擎(假定属性名称与列名称匹配),您可以执行以下操作来生成字段列表:

<bind name="objectProperties"
  value="@org.apache.commons.beanutils.BeanUtils@describe(myParameter).entrySet()" />

INSERT INTO mytable (
  <foreach index="propertyName" item="propertyValue"
    collection="objectProperties" separator=",">
        ${propertyName}
  </foreach>
)
VALUES (
  <foreach index="propertyName" item="propertyValue"
    collection="objectProperties" separator=",">
        @{propertyValue}
  </foreach>
)

Note that this was not tested and is here just to demonstrate the idea how you can approach this. 请注意,这未经测试,仅在此处说明如何实现此目的的想法。

I personally haven't used foreach as I prefer to use velocity scripting engine . 我个人还没有使用过foreach因为我更喜欢使用速度脚本引擎 With velocity scripting engine this can definitely be done: 使用速度脚本引擎,可以肯定地做到这一点:

#set( $objectProperties = $BeanUtils.describe($myParameter) )

INSERT INTO mytable (
  #foreach($property in $objectProperties)
    ${property.key}
  #end
)
VALUES (
  #foreach($property in $objectProperties)
    @{property.value}
  #end
)

You would also need to add reference to commons BeanUtils class to velocity context by adding this configuration to mybatis-velocity.properties : 您还需要通过将以下配置添加到mybatis-velocity.propertiesmybatis-velocity.properties commons BeanUtils类的引用添加到速度上下文中:

additional.context.attributes=BeanUtils:org.apache.commons.beanutils.BeanUtils

我认为您应该使用SQL语句select into来完成此要求。

your pojo s properties should be consistent with the table s columns, and the autoMapping should be true. 您的pojo s properties should be consistent with the table的列s properties should be consistent with the table ,并且autoMapping应该为true。 maybe you have to give some codes of your project,So I'll give you more advice 也许您必须为您的项目提供一些代码,所以我会给您更多建议

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM