插入一条数据后直接得到这条数据的id

今天遇到一个问题就是,想插入后继续获得主键然后再次操作!

可能有好几种方法,今天亲自测试使用的一种方法记录一下,分享给大家!

针对的数据库是MYSQ 主键自增l   以下面这个sql为例

<!-- 插入客户档案 -->
<insert id="insertCustomer" parameterType="com.cdel.module.customer.domain.Customer">
        INSERT INTO pss_basedata_customer (customerName,shortName,customerCompany,contacter,principals,cellphone,telephone,address,postcode,isArchive,auditor,auditStatus,auditTime,creator,createTime,modifier,modifyTime,status,remark,sortNum,currentDiscount,areaID,isSpecial)
        VALUES (
            #{customerName},#{shortName},#{customerCompany},#{contacter},#{principals},#{cellphone}, #{telephone},#{address},#{postcode},#{isArchive},#{auditor},#{auditStatus},#{auditTime},#{creator},#{createTime}, #{modifier},#{modifyTime},#{status},#{remark}, #{sortNum},#{currentDiscount}, #{areaID},#{isSpecial}
        )
        <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="customerID">
SELECT @@IDENTITY AS customerID
</selectKey>
    </insert>

方法:1.sql中加入:

  <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="customerID">
 SELECT @@IDENTITY AS customerID
</selectKey>

     2.在dao层接收返回的主键

public Integer insertCustomer(Customer customer) {
getSqlSession().insert("customer.insertCustomer", customer);
return customer.getCustomerID();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值