zoukankan      html  css  js  c++  java
  • mybatis 新增返回id

    第一种方式:

    在实体类的映射文件 "*Mapper.xml" 这样写:

    <insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
        insert into user(userName,password,comment)
        values(#{userName},#{password},#{comment})
    </insert>

    Tips:

    useGeneratedKeys="true" 表示给主键设置自增长
    keyProperty="userId"  表示将自增长后的Id赋值给实体类中的userId字段。
    parameterType="com.chenzhou.mybatis.User" 这个属性指向传递的参数实体类

    这里提醒下,<insert></insert> 中没有resultType属性,不要乱加。

    实体类中uerId 要有getter() and setter(); 方法

    由于我在MySQL数据库中建表时候已经设置了字段自增长,

    第二种方式:

    同样在实体类的映射文件 "*Mapper.xml" 但是要这样写:

    <!-- 插入一个商品 -->
        <insert id="insertProduct" parameterType="domain.model.ProductBean" >
           <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="productId">
              SELECT LAST_INSERT_ID()
          </selectKey>
            INSERT INTO t_product(productName,productDesrcible,merchantId)values(#{productName},#{productDesrcible},#{merchantId});
        </insert>

    Tips: 

    <insert></insert> 中没有resultType属性,但是<selectKey></selectKey> 标签是有的。

    order="AFTER" 表示先执行插入语句,之后再执行查询语句。

    可被设置为 BEFORE 或 AFTER。

    如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。

    如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 元素-这和如 Oracle 数据库相似,可以在插入语句中嵌入序列调用
    keyProperty="userId"  表示将自增长后的Id赋值给实体类中的userId字段。

    SELECT LAST_INSERT_ID() 表示MySQL语法中查询出刚刚插入的记录自增长Id.

    实体类中uerId 要有getter() and setter(); 方法

    调用:

        UserAccount userAccount1  = new UserAccount();
            userAccount1.setAccountname("test2");
            userAccount1.setPassword("test2");
            userAccount1.setRegistos("IOS");
            userAccount1.setStutas(0);
            userAccount1.setCreatetime(System.currentTimeMillis());
            userAccount1.setImei("test");
            userAccount1.setChannel("test");
            userAccount1.setRegistip("0.0.0.0");
            int i = userAccountMapper.insertSelective(userAccount1);
            System.out.println(userAccount1.getAccountid());
    
    
  • 相关阅读:
    CF 1006C Three Parts of the Array【双指针/前缀和/后缀和/二分】
    经验笔记二
    CF 1006B Polycarp's Practice【贪心】
    CF 1003D Coins and Queries【位运算/硬币值都为2的幂/贪心】
    CF 1003C Intense Heat【前缀和/精度/双层暴力枚举】
    CF 1003B Binary String Constructing 【构造/找规律/分类讨论】
    CF 1005C Summarize to the Power of Two 【hash/STL-map】
    CF 1005B Delete from the Left 【模拟数组操作/正难则反】
    CF 1005A Tanya and Stairways 【STL】
    CF 1009A Game Shopping 【双指针/模拟】
  • 原文地址:https://www.cnblogs.com/lxn0216/p/10120719.html
Copyright © 2011-2022 走看看