何隆昌 mybatis-plus新增或者修改

    科技2022-07-10  141

    有几种区别 第一种:对象或者集合有id或者无id 用 saveOrUpdate 或者saveOrUpdateBatch即可

    第二种 :集合 都 有id值,就只能遍历集合,然后用saveOrUpdate 而不能用saveOrUpdateBatch; 实体策略要用input才行(注意:不用auto的话,自增的id不会返回到实体类上)

    第三种,mapper.xml里面写sql 简单的就不多说主要是有个业务需求,当一条数据存在时update ,不存在时insert,这时就会用到 ON DUPLICATE KEY UPDATE

    @Insert({ "INSERT INTO KZT_APPSERVER_HISTORY(APPSERVERID,USERID) values(#{appid},#{userid})", "ON DUPLICATE KEY UPDATE `TIMES` = `TIMES`+1 ", }) int addHistory(@Param("userid") String userid,@Param("appid") String appid);

    TIMES=TIMES`+1 ",就是一个自增

    mybatis的写法

    <insert id="AddTeacher" parameterType="com.mycompany.entity.Teacher"> <selectKey keyProperty="count" resultType="int" order="BEFORE"> select count(*) from Teacher where teacher_id = #{teacherId} </selectKey> <if test="count > 0"> update event <set> <if test="teacherName!= null" > teacher_name= #{teacherName}, </if> </set> <where> teacher_id = #{teacherId} </where> </if> <if test="count==0"> insert into teacher(teacher_id,teacher_name) values (#{teacherId},#{teacherName}) </if> </insert>
    Processed: 0.038, SQL: 8