zoukankan      html  css  js  c++  java
  • Mybatis insert时返回自增id

    SelectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他可以很随意的设置生成主键的方式。

    详细看这里:http://www.cnblogs.com/SimonHu1993/p/7326502.html

     参考:       http://blog.csdn.net/isea533/article/details/21153791#reply 

    这种方式在mybatis insert插入时 long id=service.insert(entity);的结果永远是1,但是通过selectKey,可以获得entity自增之后的id;

                room.setPassword(password);
    				room.setIsClose(0);
    				room.setCtime(new Date());
    				roomService.insertRoom(room);
    				long roomID=room.getId();//这里能取到insert自增之后的id;

     SelectKey需要注意order属性,像MySQL一类支持自动增长类型的数据库中,order需要设置为after才会取到正确的值。

    Oracle这样取序列的情况,需要设置为before,否则会报错。

    下面是一个xml和注解的例子,SelectKey很简单,两个例子就够了:

    [html] view plain copy
     
    1. <insert id="insert" parameterType="map">  
    2.     insert into table1 (name) values (#{name})  
    3.     <selectKey resultType="java.lang.Integer" keyProperty="id">  
    4.       CALL IDENTITY()  
    5.     </selectKey>  
    6.   </insert>  

    上面xml的传入参数是map,selectKey会将结果放到入参数map中。用POJO的情况一样,但是有一点需要注意的是,keyProperty对应的字段在POJO中必须有相应的setter方法,setter的参数类型还要一致,否则会报错。

     如果是mysql的话如下 

    <insert id="insert" parameterType="entity.Room">
        insert into wsp_room (id,type,video_id, name, user_maxnum, 
          user_id, password, is_close, 
          ctime)
        values (#{id,jdbcType=BIGINT}, #{type,jdbcType=INTEGER},#{videoId,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{userMaxnum,jdbcType=INTEGER}, 
          #{userId,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{isClose,jdbcType=INTEGER}, 
          #{ctime,jdbcType=TIMESTAMP})
         <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">  
            SELECT LAST_INSERT_ID() AS  ID
        </selectKey>  
      </insert>
    [java] view plain copy
     
    1. @Insert("insert into table2 (name) values(#{name})")  
    2. @SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)  
    3. int insertTable2(Name name);  
    上面是注解的形式。
  • 相关阅读:
    MERGE同步
    SqlServer中decimal(numeric )、float 和 real 数据类型的区别
    Hashtable
    SQL Server 数据类型 float, real, money, decimal, numeric
    QA常见面试问题答与问(English)zt
    MSDN 代码审查
    security testing
    SQL Server:无日志恢复数据库
    SQL Server 2005 数据库快照(database Snapshot)
    备份和恢复概述zt
  • 原文地址:https://www.cnblogs.com/SimonHu1993/p/7326306.html
Copyright © 2011-2022 走看看