mybatis插入两个表中是否包含翻译中的forign键?

时间:2016-08-25 08:18:17

标签: java mysql mybatis

我想插入两个在事务中具有外键约束的表:

这是我的代码

@Transactional(readOnly = false)
public CuponRule save(CuponRule cuponRule, List<Cupon> cupons, List<CuponPrintRule> printRules) {
    cuponRule.preInsert();
    dao.insert(cuponRule);
    List<Long> cuponIds = new ArrayList<>();
    List<Long> printRuleIds = new ArrayList<>();
    cupons.forEach(i -> cuponIds.add(i.getCuponId()));
    dao.addCupons(cuponRule.getRuleId(), cuponIds);
    printRules.forEach(i -> printRuleIds.add(i.getPrintRuleId()));
    dao.addPrintRules(cuponRule.getRuleId(), printRuleIds);
    return cuponRule;
}

我的mapperdao.xml是

<insert id="addPrintRules">
    INSERT INTO pri_print_rule_cupon_rule(
    print_rule_id,
    rule_id
    )VALUES
    <foreach collection="printRules" item="id" separator=",">
        (#{0},#{id})
    </foreach>
</insert>

<insert id="addCupons">
    INSERT INTO pri_cupon_cupon_rule(
    cupon_id,
    rule_id
    )VALUES
    <foreach collection="cupons" index="id" separator=",">
        (#{id},#{0})
    </foreach>
</insert>

<insert id="insert" useGeneratedKeys="true" keyProperty="ruleId">
    INSERT INTO pri_cupon_rule(
    rule_name,
    rule_leave,
    rule_scope,
    rule_status,
    start_time,
    end_time,
    create_by,
    create_date,
    update_by,
    update_date,
    remarks,
    del_flag
    )VALUES (
    #{ruleName},
    #{ruleLeave},
    #{ruleScope},
    #{ruleStatus},
    #{startDate},
    #{endDate},
    #{createBy.id},
    #{createDate},
    #{updateBy.id},
    #{updateDate},
    #{remarks},
    #{DEL_FLAG_NORMAL}
    )
</insert>

但我收到的错误信息是

  

引起:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败(dadi-uatpri_cupon_cupon_rule,CONSTRAINT FK_cupon_rule_cupon_ref外键(cupon_id)参考pri_cuponcupon_id))

我怎么能解决这个问题?

0 个答案:

没有答案