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

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
}

 

posted @ 2018-03-15 20:54  方方方方方方  阅读(170)  评论(0编辑  收藏  举报