0

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?

BaiJiFeiLong
  • 3,716
  • 1
  • 30
  • 28

3 Answers3

1

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

I think you should using the SQL statement select into to complete this requirement.

bcperth
  • 2,191
  • 1
  • 10
  • 16
David
  • 9
  • 2
  • 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
-1

your pojos properties should be consistent with the tables columns, and the autoMapping should be true. maybe you have to give some codes of your project,So I'll give you more advice

Curllen
  • 11
  • 1