[英]How to iterate all properties/fields in bean/Object, includes reference Object/Bean
[英]How to use MyBatis to iterate all fields of an object?
我想将对象的所有字段插入一行,但是我不知道确切的文件名。 MyBatis支持吗?
Mybatis在期望表达的地方(包括foreach
collection
属性)使用OGNL 。
OGNL 允许调用静态方法,因此您可以利用它。
使用默认脚本引擎(假定属性名称与列名称匹配),您可以执行以下操作来生成字段列表:
<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
因为我更喜欢使用速度脚本引擎 。 使用速度脚本引擎,可以肯定地做到这一点:
#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
, mybatis-velocity.properties
commons BeanUtils
类的引用添加到速度上下文中:
additional.context.attributes=BeanUtils:org.apache.commons.beanutils.BeanUtils
我认为您应该使用SQL语句select into
来完成此要求。
您的pojo s properties should be consistent with the table
的列s properties should be consistent with the table
,并且autoMapping应该为true。 也许您必须为您的项目提供一些代码,所以我会给您更多建议
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.