關於在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一下便可支持
對於mappermybatis

/**
 * 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值app

@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下測試經過ide

相關文章
相關標籤/搜索