【转载】mybatis根据条件判断来执行插入或者更新

转自:https://blog.csdn.net/qq_20867981/article/details/80422824

 <insert id="updateOrInsertPhone2Email" useGeneratedKeys="true" keyProperty="id" parameterType="com.sa.pojo.Phone2Email" >
    <!-- 查看是否存在memberid,如果存在及更新,否则插入 -->
    <selectKey keyProperty="count" order="BEFORE" resultType="int">
      select count(*) as count from phone2email where phone = #{phone,jdbcType=VARCHAR}
    </selectKey>
 
    <!-- 如果大于0则更新 -->
    <if test="count>0">
      update phone2email set email=#{email,jdbcType=VARCHAR} where phone = #{phone,jdbcType=VARCHAR}
    </if>
 
    <!-- 如果等于0则保存 -->
    <if test="count==0">
      insert into phone2email(phone,email)
      values(#{phone,jdbcType=VARCHAR},#{email,jdbcType=VARCHAR})
    </if>
 
  </insert>
这里的count要有setter方法,也就是要作为Phone2Email(对象)的属性:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Phone2Email {
    private Integer id;
 
    private String phone;
 
    private String email;
 
    private int count;
 
 
 }

如果没有则会报错:

Caused by: org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty 'count' in com.sa.pojo.Phone2Email.

在使用mybatis时,常常会出现这种需求:
当主键是自增的情况下,添加一条记录的同时,其主键是不能使用的,但是有时我们需要该主键,这时我们该如何处理呢?这时我们只需要在其对应xml中加入以下属性即可:

useGeneratedKeys="true"  keyProperty="对应的主键的对象"。

如下例:

<!--   主要是在主键是自增的情况下,添加成功后可以直接使用主键值,其中keyProperty的值是对象的属性值不是数据库表中的字段名-->
    <insert id="saveMsg" parameterType="cn.com.hyddl.smarthome.notice.core.nano.Notice"
        useGeneratedKeys="true" keyProperty="msgId">
        insert into notice(msg_type,title,content,rec_time,send_time,user_id,deleted,viewed)
        values(#{msgType,jdbcType=INTEGER},#{title,jdbcType=VARCHAR},#{content,jdbcType=VARCHAR},
               #{recTime,jdbcType=BIGINT},#{sendTime,jdbcType=BIGINT},#{userId,jdbcType=VARCHAR},
               #{deleted,jdbcType=TINYINT},#{viewed,jdbcType=INTEGER})
    </insert>

这样在之后的java代码中我们就可以获取该主键对应的对象的属性值(msgId)

猜你喜欢

转载自www.cnblogs.com/HKnight/p/12957187.html