mybatisintersystems-cache

mybatis foreach but submiting individual inserts


The following mybatis mapping works on all our supported databases except for one. This is because that database does not allow a bulk insert method (Intersystems Cache). Because of that I'd like to submit individual insert statements instead rather than one. How could I structure this mybatis statement so that it still reads from my java.util.List but it does multiple inserts?

  <insert id="bulkInsert" parameterType="java.util.List" >
    <foreach collection="list" item="resource" index="index">
      INSERT INTO ${prefix}ACT_APP_DEPLOYMENT_RESOURCE(ID_, NAME_, RESOURCE_BYTES_, DEPLOYMENT_ID_) VALUES
      (#{resource.id, jdbcType=VARCHAR},
      #{resource.name, jdbcType=VARCHAR},
      #{resource.bytes, jdbcType=${blobType}},
      #{resource.deploymentId, jdbcType=VARCHAR})
    </foreach>
  </insert>

Solution

  • If you are using java version 8+ you can use default method in mapper like this:

    interface MyMapper {
        void insertResource(@Param("resource") MyResource resource);
    
        default void bulkInsert(List<MyResource> resources) {
             for(MyResource resource:resources) {
                 insertResource(resource);
             }
        }
    }
    

    And modify the mapper xml:

    <insert id="insertResource">
        INSERT INTO ${prefix}ACT_APP_DEPLOYMENT_RESOURCE(ID_, NAME_, RESOURCE_BYTES_, DEPLOYMENT_ID_) VALUES
        (#{resource.id, jdbcType=VARCHAR},
        #{resource.name, jdbcType=VARCHAR},
        #{resource.bytes, jdbcType=${blobType}},
        #{resource.deploymentId, jdbcType=VARCHAR})
    </insert>