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?
-
Please give an example of your class and your table columns – Bejond Nov 01 '18 at 06:03
-
Please add some code of your's so that I can give you some examples. – Pawan Tiwari Nov 01 '18 at 09:33
3 Answers
Mybatis uses OGNL in places where expression is expected including collection
attribute of the foreach
.
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.
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
)
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

- 14,905
- 3
- 48
- 53
I think you should using the SQL statement select into
to complete this requirement.
-
Welcome to Stackoverflow. Your answer would be improved by showing some example code. The question is specifically about MyBatis and I wonder if your answer addresses this. – bcperth Nov 01 '18 at 06:39
your pojos properties should be consistent with the table
s columns, and the autoMapping should be true. maybe you have to give some codes of your project,So I'll give you more advice

- 11
- 1