mybatis 插入操作实现主键返回的方法

mybatis 插入操作实现主键返回的方法

 <insert id="insert" parameterType="org.test.entity.PersonEO" >
    <selectKey keyProperty="pk_person" order="BEFORE" resultType="java.lang.String" >
    select sys_guid() from dual
    </selectKey>

    insert into T_IN_MESSAGE (pk_person,id,name)
    values (#{pk_person,jdbcType=CHAR}, #{id,jdbcType=CHAR}, #{name,jdbcType=VARCHAR},)

  </insert>

更新-----------时间2018.5.22

插入语句映射

插入语句和查询语句类似,也需要定义唯一的id,指定传入参数类型。

[html]  view plain  copy
  1. <!-- 写入新记录并返回主键值,注意,这里的KeyProperty应该是Java类里的属性名称,而非数据表中的字段名 -->  
  2. <insert id="insertUser" parameterType="User" useGeneratedKeys="true"  
  3.     keyProperty="userId">  
  4.     INSERT INTO sys_user(user_name, user_password, nick_name,  
  5.     user_type_id, is_valid, created_time)  
  6.     VALUES(#{userName},  
  7.     #{userPassword}, #{nickName}, #{userTypeId}, #{isValid},  
  8.     #{createdTime})  
  9. </insert>  

针对插入语句,这里有一点需要进行特别说明,那就是如何获得新插入数据的主键值。

在允许使用自增长字段做为主键的数据库中(如MSSQL,Mysql),我们只需要在insert元素中增加两个属性值即可。如:

[html]  view plain  copy
  1. <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="userId">  
将属性 userGeneratedKeys 设为true,并将 KeyProperty 属性设为数据表主键对应的实体对象属性名称。这句话有点绕,我们就以上面这条插入语句为例,数据表中主键是user_id,对应的实体对象中的属性名称是userId,所以这里我们就把userId高为 KeyProperty 的值。

在不允许有自增字段的数据库中(如Oracle数据库),Mybatis有另外一种方法生成数据表主键,即在insert元素内部增加一个selectKey元素,用于生成数据表主键。如

[html]  view plain  copy
  1. <insert id="insertUser" parameterType="User">  
  2.     <selectKey keyProperty="userId" resultType="int" order="BEFORE">  
  3.         select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1  
  4.     </selectKey>  
  5.     INSERT INTO sys_user(user_name, user_password, nick_name,  
  6.     user_type_id, is_valid, created_time)  
  7.     VALUES(#{userName},  
  8.     #{userPassword}, #{nickName}, #{userTypeId}, #{isValid},  
  9.     #{createdTime})  
  10. </insert>  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值