本文介绍了如何使用MyBatis迭代对象的所有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将对象的所有字段插入一行,但是我不知道确切的文件名. MyBatis支持吗?

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使用 OGNL 在需要表达的地方,包括foreachcollection属性.

Mybatis uses OGNL in places where expression is expected including collection attribute of the foreach.

OGNL 允许调用静态方法,因此您可以利用它.

OGNL allows to invoke static methods so you can leverage this.

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

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.

我个人没有使用foreach,因为我更喜欢使用速度脚本引擎.借助速度脚本引擎,可以肯定地做到这一点:

I personally haven't used foreach as I prefer to use velocity scripting engine. 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
)

您还需要通过将以下配置添加到mybatis-velocity.properties来向速度上下文添加对commons BeanUtils类的引用:

You would also need to add reference to commons BeanUtils class to velocity context by adding this configuration to mybatis-velocity.properties:

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

这篇关于如何使用MyBatis迭代对象的所有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:28