mybatis 插入或者更新

本文介绍了一种使用MyBatis实现的根据手机号码更新电子邮件地址或在不存在时插入新记录的方法。通过一个示例展示了如何使用<selectKey>进行计数查询并依据结果决定执行更新或插入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  <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.

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值