首页 技术 正文
技术 2022年11月19日
0 收藏 390 点赞 4,502 浏览 1542 个字

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

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

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

这种方式在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很简单,两个例子就够了:

  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>
  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);

上面是注解的形式。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,580
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918