无法使用MyBatis批量插入Oracle DB

时间:2014-10-09 12:32:22

标签: java spring oracle mybatis ibatis

我尝试使用MyBatis(与Spring集成)在Oracle数据库中批量插入表。

这是mapper接口中方法的定义:

public void savePayments(@Param("payments") List<MassPaymentItem> payments);

这是一个MyBatis XML映射器代码:

<insert id="savePayments" parameterType="MassPaymentFileItem" useGeneratedKeys="false">
    INSERT INTO mass_payments
        (payment_id, file_id, msisdn, amount, status)
    <foreach collection="payments" item="payment" index="index" separator=" UNION ALL ">
        SELECT SEQ_MASS_PAYMENT.nextval, #{payment.fileId}, #{payment.msisdn}, #{payment.amount}, 0 FROM DUAL
    </foreach>
</insert>

当我执行这个时,我收到MyBatisSystemException,消息“嵌套异常是org.apache.ibatis.builder.BuilderException:不正确的内联参数映射格式。应该是:#{propName,attr1 = val1,attr2 = val2}”

有什么问题?如何解决?

3 个答案:

答案 0 :(得分:1)

我找到了解决方案here

<insert id="savePayments">
   INSERT ALL
   <foreach collection="payments" item="payment">
   INTO
      mass_payments_t (payment_id, file_id, msisdn, amount)
   VALUES
      (seq_mass_payment.nextval, #{payment.fileId, javaType=Integer, jdbcType=NUMERIC}, #{payment.msisdn, javaType=String, jdbcType=VARCHAR}, #{payment.amount, javaType=BigDecimal, jdbcType=NUMERIC})
   </foreach>
   SELECT * FROM dual
</insert>

答案 1 :(得分:1)

我发现第一个答案对我不起作用,然后我找到另一个解决方案如下:

 <insert id="savePayments" parameterType="java.util.List" useGeneratedKeys="true">
       <selectKey resultType="java.lang.Integer" keyProperty="payment_id"
            order="BEFORE">
            SELECT SEQ_MASS_PAYMENT.nextval as payment_id FROM DUAL
        </selectKey>
        INSERT INTO mass_payments
            (payment_id, file_id, msisdn, amount, status)
            select SEQ_MASS_PAYMENT.nextval, A.* from (
        <foreach collection="payments" item="payment" index="index" separator="UNION ALL">
            SELECT 
            #{payment.fileId} as file_id,
            #{payment.msisdn} as msisdn,
            #{payment.amount} as amount,
            0 as status
            FROM DUAL
        </foreach> ) A
    </insert>

答案 2 :(得分:0)

仔细查看您的select语句。如果想要列名或函数,则传递参数。你应该把它改成类似的东西(注意from的位置:

<foreach collection="payments" item="payment" index="index" separator=" UNION ALL ">
        (SELECT SEQ_MASS_PAYMENT.nextval from DUAL), #{payment.fileId}, #{payment.msisdn}, #{payment.amount}, 0 
    </foreach>