2

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

1
  • Can you post the code(structure and the content) of your HashMap? You can also set your MyBatis logging level to show the query that is generated. mybatis.github.io/mybatis-3/logging.html Commented Sep 17, 2014 at 7:14

1 Answer 1

7

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Many many thanks... it's working... I tried lot of things... you saved me... thanks once again...How can I missed the "String Substitution" section from the documentation...my bad..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.