mybatish2db

Insert list of records using mybatis


I am trying to insert records into a table from a list using Mybatis. I use mybatis velocity as scripting language. Looks like the problem is in the parameter symbol #. I tried to replace that with @ since I'm using mybatis velocity but nothing worked. Could someone please help me out.

Mapper.java:

void insertFileVersions(@Param("versionsList") List<Integer> activeFileVersions);

mapper.xml:

<insert id="insertFileVersions" parameterType="java.util.List">
<foreach collection="versionsList" item="version" index="index">
    INSERT INTO FILE_TEMP (FILE_ID, FILE_VERSION) VALUES (#{version.fileId}, #
{version.fileVersion})
</foreach>
</insert>

I get the error Cause: org.h2.jdbc.JdbcSQLException: Column "VERSION.FILEID" not found; SQL statement


Solution

  • This is all wrong for Velocity - you are using the XML language driver syntax. With the Velocity language driver, you use @{...} instead of #{...}, and you also use #repeat instead of <foreach>. See this page for some examples: http://www.mybatis.org/velocity-scripting/

    But please consider writing your code differently and using MyBatis' batch capabilities, rather then generating one giant statement. See this FAQ for an example: https://github.com/mybatis/mybatis-3/wiki/FAQ#how-do-i-code-a-batch-insert