Mybatis插入数据返回主键ID
Posted jimmyshan-study
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis插入数据返回主键ID相关的知识,希望对你有一定的参考价值。
<insert id="add" parameterType="com.dsa.core.base.model.ProductSync">
insert into tm_sync_product(
<if test="productId!=null">product_id,</if>
<if test="mainLimit!=null">main_limit,</if>
<if test="productName!=null">product_name,</if>
<if test="productBrand!=null">product_brand,</if>
<if test="profitType!=null">profit_type,</if>
<if test="deadLine!=null">dead_line,</if>
<if test="productStartDay!=null">product_start_day,</if>
<if test="productEndDay!=null">product_end_day,</if>
<if test="buyStartDay!=null">buy_start_day,</if>
<if test="buyEndDay!=null">buy_end_day,</if>
<if test="riskRank!=null">risk_rank,</if>
<if test="redeemFlg!=null">redeem_flg,</if>
<if test="productStatus!=null">product_status,</if>
<if test="startAmount!=null">start_amount,</if>
<if test="addAmount!=null">add_amount,</if>
<if test="yearRate!=null">year_rate,</if>
<if test="productNote!=null">product_note,</if>
<if test="otherBankBuy!=null">other_bank_buy,</if>
<if test="otherBankAmt!=null">other_bank_amt,</if>
<if test="rateVal!=null">rate_val,</if>
<if test="recordFlg!=null">record_flg</if>
) values (
<if test="productId!=null">#{productId},</if>
<if test="mainLimit!=null">#{mainLimit},</if>
<if test="productName!=null">#{productName},</if>
<if test="productBrand!=null">#{productBrand},</if>
<if test="profitType!=null">#{profitType},</if>
<if test="deadLine!=null">#{deadLine},</if>
<if test="productStartDay!=null">#{productStartDay},</if>
<if test="productEndDay!=null">#{productEndDay},</if>
<if test="buyStartDay!=null">#{buyStartDay},</if>
<if test="buyEndDay!=null">#{buyEndDay},</if>
<if test="riskRank!=null">#{riskRank},</if>
<if test="redeemFlg!=null">#{redeemFlg},</if>
<if test="productStatus!=null">#{productStatus},</if>
<if test="startAmount!=null">#{startAmount},</if>
<if test="addAmount!=null">#{addAmount},</if>
<if test="yearRate!=null">#{yearRate},</if>
<if test="productNote!=null">#{productNote},</if>
<if test="otherBankBuy!=null">#{otherBankBuy},</if>
<if test="otherBankAmt!=null">#{otherBankAmt},</if>
<if test="rateVal!=null">#{rateVal},</if>
<if test="recordFlg!=null">#{recordFlg}</if>
)
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
select last_insert_id() as id
</selectKey>
</insert>
注意:(此处为mysql)这里的selectKey的resultType 必须和实体对象中的id类型一致,否则报错。
oracle的如下:
<selectKey resultType="java.lang.Long" keyProperty="ID" order="AFTER">
SELECT IBOKEE_COMM_TAG_LIBRARY_SEQ.nextval AS Id FROM DUAL
</selectKey>
实体类
public class ProductSync implements Serializable {
private Long id;
...
...
}
dao Mapper
public interface ProductSyncMapper {
/**
* @param product Object
* 新增纪录
*/
public void add(ProductSync product);
}
以上是关于Mybatis插入数据返回主键ID的主要内容,如果未能解决你的问题,请参考以下文章