插入一条数据后直接得到这条数据的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();
}

猜你喜欢

转载自blog.csdn.net/qq_34468186/article/details/80475480