关于在Mybatis和Mapper下的Postgresql自增主键Insert后取值的问题

传统的xml形式

  <insert id="insert" parameterType="com.xxxxx.model.UserBankAccount" useGeneratedKeys="true" keyProperty="id" keyColumn="id" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into hxc.user_bank_account (bank_account, fund_id, validity_period, 
      deleted, bank_id, full_name, 
      is_default, deposit_bank, province, 
      city)
    values (#{bankAccount,jdbcType=VARCHAR}, #{fundId,jdbcType=BIGINT}, #{validityPeriod,jdbcType=DATE}, 
      #{deleted,jdbcType=INTEGER}, #{bankId,jdbcType=INTEGER}, #{fullName,jdbcType=VARCHAR}, 
      #{isDefault,jdbcType=INTEGER}, #{depositBank,jdbcType=VARCHAR}, #{province,jdbcType=VARCHAR}, 
      #{city,jdbcType=VARCHAR})
  </insert>

如果用注解的话,特别是选择tk.mybatis.mapper的话,可能对POSTGRESQL的自增主键支持并不好。只需要稍buff一下即可支持
对于mapper

/**
 * DAO of `sms_send_result`
 * 
 * @author 袁贵
 * @version 1.0
 * @since 1.0
 */
public interface SmsSendResultMapper extends Mapper<SmsSendResult> {
    
    @InsertProvider(type = BaseInsertProvider.class, method = "dynamicSQL")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    @Override
    int insertSelective(SmsSendResult record);
    
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    @InsertProvider(type = BaseInsertProvider.class, method = "dynamicSQL")
    @Override
    int insert(SmsSendResult record);

}

对于entity,在生成insert动态SQL时,忽略ID字段,然后就会自动取值数据库里的bigserial类型的ID值

@Table(name = "sms_send_result", schema = "sms")
public class SmsSendResult {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column sms.sms_send_result.id
     *
     * @mbggenerated
     */
    @Id
    @Column(insertable = false)
    private Long id;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column sms.sms_send_result.telephone
     *
     * @mbggenerated
     */
    private String telephone;
.....
}

以上代码在mybatis3.4.5+mapper3.4.5下测试通过

    原文作者:ccfish
    原文地址: https://segmentfault.com/a/1190000011757933
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞