如何使用MyBatis遍历一个对象的所有字段?

How to use MyBatis to iterate all fields of an object?

我想将一个对象的所有字段插入一行,但我不知道确切的字段名称。 MyBatis 支持吗?

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

你的 pojos properties should be consistent with the tables 列,自动映射应该是正确的。可能你要给你项目的一些代码,所以我会给你更多的建议

Mybatis 在需要表达式的地方使用 OGNL 包括 foreachcollection 属性。

OGNL allows 调用静态方法以便您可以利用它。

使用默认脚本引擎(假设属性名称与列名称匹配),您可以执行类似这样的操作来生成字段列表:

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

请注意,这还没有经过测试,只是为了演示您如何处理这个问题。

我个人没有使用 foreach,因为我更喜欢使用 velocity scripting engine。使用速度脚本引擎,这绝对可以做到:

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

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

您还需要通过将此配置添加到 mybatis-velocity.properties:

,将对 commons BeanUtils class 的引用添加到 velocity 上下文
additional.context.attributes=BeanUtils:org.apache.commons.beanutils.BeanUtils