mybatis insert 返回主键

xiaoxiao2021-02-28  120

如题,我想在insert的时候返回主键,在*Mapper.xml里可以这么写

<insert id="insert" parameterType="com.springmvc.lxf.entity.Person" > <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() </selectKey> insert into person (id, name, sex, age) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}) </insert>

我主要的是加了个selectKey,里面的keyProperty属性就是我的主键id

或者:

<insert id="insert" parameterType="com.springmvc.lxf.entity.Person" useGeneratedKeys="true" keyProperty="id" > insert into person (id, name, sex, age) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}) </insert>

这里设置为自动生成主键并映射回id字段

使用的时候这么使用:

Person person=new Person(); person.setAge(15); person.setName("test"); person.setSex("男"); System.out.println("insert之前:"+person); System.out.println(personMapper.insert(person)); System.out.println("insert之后:"+person);

他都会把新增记录的主键id返回到person的id属性里面去

转载请注明原文地址: https://www.6miu.com/read-41231.html

最新回复(0)