zoukankan      html  css  js  c++  java
  • MyBatis返回插入的主键ID

    使用MyBatis,通常我们都会执行这一步新增的操作:

    int count = this.projectMapper.addProject(projectBuildingInfoVO);
    

    count 表示影响的行数。
    在将VO对象传到mapper层的时候,projectBuildingInfoVO 并没有id,id设置的是自增。

    需求:使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。

    一、xml方式

    <insert id="addProject" parameterType="com.coolead.module.model.vo.ProjectBuildingInfoVO">
    
        <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
        
        insert into tb_project
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">id,</if>
            <if test="fullName != null">full_name,</if>
            ......
            ......
    </insert>
    

    关键代码就是<selectKey>这段,keyProperty表示的是VO对象中id属性的属性名,SELECT LAST_INSERT_ID()表示的就是最后插入的这条数据的主键id.

    这样新增之后,projectBuildingInfoVO对象就有id了。

    二、注解方式

    @Insert("insert into tb_user(xx,xx) values(#{xx},#{xx})") 
    @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false, resultType = int.class) 
    Integer save(User user);
    
  • 相关阅读:
    Junit。。。
    TCP
    InetAddress
    URL
    【转】Hello SDL
    批量移动文件
    在阿里云Ubuntu 14.04.5 LTS下安装nethogs0.8.5
    十二银元分三次找一假
    SQL解析
    POI
  • 原文地址:https://www.cnblogs.com/VitoYi/p/7852758.html
Copyright © 2011-2022 走看看