MySQLIntegrityConstraintViolationException:栏''不能为空

时间:2018-09-10 11:03:10

标签: mysql case mybatis case-when

mapper:
<update id="updateSurplusAmountByPrimaryKeyAndMaterialTypeId" 
  parameterType="java.util.List">
    update db_logistics.table_inventory_material
    set surplusAmount=
    <foreach collection="list" item="item" index="index"
             separator=" " open="case" close="end">
        when inventoryId=#{item.inventoryId} and materialTypeId=# 
    {item.materialTypeId} then #{item.surplusAmount,jdbcType=INTEGER}
    </foreach>
    where inventoryId in
    <foreach collection="list" index="index" item="item"
             separator="," open="(" close=")">
        #{item.inventoryId,jdbcType=BIGINT}
    </foreach>
</update>
 fun updateSurplusAmountByPrimaryKeyAndMaterialTypeId(records: 
List<InventoryMaterial>): Int
data class InventoryMaterial(
    var inventoryId: Int = 0,
    var materialTypeId: Int = 0,
    var surplusAmount: Int = 0,
    var consumeSpeed: Float = 0f,
    var consumeAlarmDayCount: Int = 0,
    var updateDataTime: LocalDateTime =  LocalDateTime.now())

错误

“原因:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列'surplusAmount'不能为空”

当我将when inventoryId=#{item.inventoryId} and materialTypeId=#{item.materialTypeId} 修改为when inventoryId=#{item.inventoryId} 时,错误消失了。 但我需要拖曳参数stockstockId和materialTypeId才能决定库存ID。有人可以给我答案吗?

1 个答案:

答案 0 :(得分:0)

执行的查询通过table_inventory_materialinventoryId中选择记录,并使用每个materialTypeId的指定数据对其进行更新。

之所以会发生此问题,是因为对于您在列表中传递的某些inventoryId,数据库中的materialTypeId数比您在列表中作为参数传递的数量要多。

因此,生成的case语句会为丢失的NULL产生materialTypeId,并且尝试将surplusAmount设置为NULL会导致错误。