Mybatis insert时返回自增id

xiaoxiao2021-02-28  85

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   <insert id="insert" parameterType="map">      insert into table1 (name) values (#{name})      <selectKey resultType="java.lang.Integer" keyProperty="id">        CALL IDENTITY()      </selectKey>    </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   @Insert("insert into table2 (name) values(#{name})")  @SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)  int insertTable2(Name name);   上面是注解的形式。
转载请注明原文地址: https://www.6miu.com/read-79735.html

最新回复(0)