mybatis中Insert语句如何返回插入的主键

方法一:

mapper.java

    /**
     * 添加部门
     * @param department
     * @return
     */
    Integer insertDep(Department department);

xml

    <insert id="insertDep" parameterType="com.example.pojo.entity.Department">
        <selectKey keyProperty="departmentId" order="AFTER" resultType="java.lang.Integer ">
            select LAST_INSERT_ID()
        </selectKey>
        insert into sys_department(name,parentId,enabled,isParent)
        VALUES(#{name},#{parentId},1,0)
    </insert>

其中:

selectKey标签:将插入到数据库的某条记录的主键,返回到指定对象(user)对应属性中。
keyProperty:  指定返回的主键,存储在对象中(user)的哪个属性
order:相对于insert语句,selectKey标签中的sql的执行顺序。由于mysql的自增原理,执行完insert语句之后才将主键生成,所以这里selectKey的执行顺序为after。
resultType:  返回的主键对应的JAVA类型
LAST_INSERT_ID():  是mysql的函数,返回auto_increment自增列新记录id值。

 方法二

使用:

useGeneratedKeys="true" keyProperty="departmentId"
    <insert id="insertDep" parameterType="com.example.pojo.entity.Department" useGeneratedKeys="true" keyProperty="departmentId">
        insert into sys_department(departmentId,name,parentId,enabled,isParent)
        VALUES(uuid(),#{name},#{parentId},1,0)
    </insert>

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值