在mysql插入操作时,我们会遇到已经存在数据的处理问题,
对于这种问题,有两种处理方法(前提是数据都有唯一索引,如主键或自建的唯一索引):
1、ignore,对新数据做忽略处理
如:
<insert id="insertIgnore"> INSERT ignore INTO stu (no,name,age,tuition,gender) VALUES(#{stu.no},#{stu.name},#{stu.age},#{stu.tuition},#{stu.gender}); </insert>2、on duplidate key update 对旧数据做更新处理
如:
<insert id="upsert"> INSERT ignore INTO stu (no,name,age,tuition,gender) VALUES(#{stu.no},#{stu.name},#{stu.age},#{stu.tuition},#{stu.gender}) on duplicate key update name=values(name), age=values(age) </insert>需要注意是,on duplicate key update 更新的字段必须在插入字段里存在才行