mybatis 插入数据返回主键

本文介绍如何使用MyBatis在插入数据后返回自动生成的主键。通过在mapper.xml文件中添加selectKey标签,并设置相应的属性,可以在执行插入操作后获取到新生成的主键ID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有的时候我们会有插入数据返回主键的需求  这个很简单  只需要两步操作

1.修改mapper.xml  在insert前面加一个标签 selectKey
   order的意思是在增加表操作之后  resultType是操作表id的属性 一般是int long  keyPropperty是主键的名称 一般是id  

SELECT LAST_INSERT_ID() 表示查询最后一次增加的id
  <insert id="insertSelective" parameterType="com.hangzhi.bean.Parent" >
  	<selectKey keyProperty="id" resultType="int" order="AFTER">
  		SELECT LAST_INSERT_ID()
  	</selectKey>
    insert into parent
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="phone != null" >
        phone,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="gender != null" >
        gender,
      </if>
      <if test="email != null" >
        email,
      </if>
      <if test="type != null" >
        type,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="phone != null" >
        #{phone,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="gender != null" >
        #{gender,jdbcType=TINYINT},
      </if>
      <if test="email != null" >
        #{email,jdbcType=VARCHAR},
      </if>
      <if test="type != null" >
        #{type,jdbcType=TINYINT},
      </if>
    </trim>
  </insert>

2. 我们就可以直接在java代码中获取这个id了 如下红色的部分, 就是在插入之后,用直接用对象的getId()获取就可以了.是不是很简单呢

	public int addParent(Parent parent) {
		parentMapper.insertSelective(parent);
		int id = parent.getId();
		System.out.println("添加的家长id="+id);
		return id;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值