描述:
通常情况下,我们会先通过条件去数据库查一次,根据返回的结果,如果为空则执行insert动作,如果不为空则执行update动作,这样的做法难免显得有些臃肿。其实我们可以通过 ON DUPLICATE KEY 关键字用一句相当简单的sql来实现相同的效果。下面就详细说一下用法。
前提条件:
查询条件为主键或唯一索引
新增数据
/*
添加返回主键
*/
@Insert("insert into student(username,password,name,code) value(#{username_p},#{password_p},#{name_p},#{code_p})")
@Options(keyColumn = "id",keyProperty = "id_p",useGeneratedKeys = true)
Integer insertStudent1(Student student);
说明:code为唯一索引
再次新增数据
/*
添加:如果存在就修改,不存在就新增
*/
@Insert("insert into student(username,password,name,code) value" +
"(#{username_p},#{password_p},#{name_p},#{code_p})" +
"ON DUPLICATE KEY UPDATE name = #{name_p},username = #{username_p}, password = #{password_p}")
@Options(keyColumn = "id",keyProperty = "id_p",useGeneratedKeys = true)
Integer insertStudent2(Student student);
注意事项:这种方法虽然可以减少部分代码量,但仅适用于表结构稳定的情况,因为如果后来表中再删除了唯一索引,那么这条sql就存在着失效的风险。