mysql插入存在即更新,mybatis xml动态sql插入存在即更新

方法1:使用replace into 插入,该条语句可以在索引或主键有冲突的情况下,删除已存在的记录,然后插入新记录。

:replace into tableName(col1,col2,col3) values ()

方法2:使用ON DUPLICATE KEY UPDATE,如果主键存在,即更新表

mybatis xml文件写法如下:

id="insertOrUpdate" parameterType="xxxxx">
    INSERT into case_warning_rule (
    case_definition_dept_id,
    commitment_day,
    legal_period,
    approval_day,
    approval_warning,
    commitment_warning,
    commitment_unusual,
    legal_warning,
    legal_unusual,
    update_time
    ) VALUES (
    #{caseDefinitionDeptId},
    #{commitmentDay},
    #{legalPeriod},
    #{approvalDay},
    #{approvalWarning},
    #{commitmentWarning},
    #{commitmentUnusual},
    #{legalWarning},
    #{legalUnusual},
    #{updateTime}
    ) ON DUPLICATE KEY UPDATE
    commitment_day =VALUES (commitment_day),
    legal_period =VALUES (legal_period),
    approval_day =VALUES (approval_day),
    approval_warning =VALUES (approval_warning),
    commitment_warning =VALUES (commitment_warning),
    commitment_unusual =VALUES (commitment_unusual),
    legal_warning =VALUES (legal_warning),
    legal_unusual =VALUES (legal_unusual),
    update_time =VALUES (update_time)

你可能感兴趣的:(SQL,java)