mybatis插入操作时,返回自增主键id

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:34   1504   0

mapper.xml 代码

<insert id="insert" parameterType="com.Student" >
    <selectKey keyProperty="id" resultType="long" order="AFTER">
        select last_insert_id();
    </selectKey>
    insert into student(id,, name)
    values (#{id,jdbcType=BIGINT},#{name,jdbcType=VARCHAR});
</insert>

分析 xml

keyProperty:pojo主键的属性
resultType:pojo主键类型
order:<selectKey> 语句是在插入语句执行之前执行,还是执行之后执行
    BEFORE:之前(一般 UUID 主键)
    AFTER:之后(一般自增的主键)
select last_insert_id();获得当前事务中,最后生成的主键

java 代码

@Override
public Map addContentCategory(long id, String name) {
    Student s = new Student();
    s.setId(id);
    s.setName(name); 
    //插入到数据库(返回的主键,会自动封装到 s 里面)  
    studentMapper.insert(s); 

    Map map = new HashMap();
    map.put("data",s);
    return map
}

转载于:https://www.cnblogs.com/fangwu/p/8576224.html

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP