简体   繁体   中英

How to pass dynamic fields and values using mybatis 3

I am new to Java and mybatis3. On a project I am using mybatis3..

say I have database table named "t". There are several columns.

In the project I will send a hashmap (contains 2 ArrayList of key, value) to mapper.xml. From there it will get 2 array contain keys of columns names, and values of columns...

I want to inset into that table... by that, I think I will able to dynamically insert data and partially update some column data... with update... but getting sql syntax error...

My existing code of mapper.xml

<insert id="createNews" parameterType="map" useGeneratedKeys="true" keyColumn="id">
  INSERT INTO t
    <foreach item="key" collection="Key" index="index" open="(" separator="," close=")">
        #{key}
    </foreach>
    VALUES
    <foreach item="value" collection="Value" index="index" open="(" separator="," close=")">
        #{value}
    </foreach>
  ;
</insert>

partial error stackTrace....

### Error updating database.  Cause:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''name'
     ) 
    VALUES
     (  
        'some value'
    ' at line 3

But when I hard code the column name its working correctly... How can I insert dynamically...

Note: I googled, but unable to find... I don't want to use any pojo or annotation... thanks in advance...

Not sure, but I'll take a shot. When you use #{key} , MyBatis puts extra '' around it if it is a String , Date etc. If you give your column names with a variable you need to use direct String replacement which is ${key} .

The error log says something like ...right syntax to use near ''name') VALUES ('some value'...

Can you try

<insert id="createNews" parameterType="map" useGeneratedKeys="true" keyColumn="id">
  INSERT INTO t
    <foreach item="key" collection="Key" index="index" open="(" separator="," close=")">
        ${key}
    </foreach>
    VALUES
    <foreach item="value" collection="Value" index="index" open="(" separator="," close=")">
        #{value}
    </foreach>
</insert>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM