MyBatis与Oracle,MySql,SqlServer插入数据返回主键方式

MyBatis与Oracle,MySql,SqlServer插入数据返回主键方式

MyBatis Oracle MySql SqlServer 插入 返回主键


MyBatis在insert插入数据时,返回一个自增的主键。可以通过XML的配置来实现,而数据库的不同配置有所不同,我们来看看。

Oracle

相对于MySql,Sql Server来说,Oracle插入主键返回自增稍显复杂一点,需要一个Sequence和一个Trigger,接下来看代码。Sequence:序列号,创建一个自增的序列号。
Trigger:当做insert操作的时候,触发插入一个从Sequence中获取序列插入主键中。

  • Sequence:
create sequence Seq_Test
minvalue 1
maxvalue 100000000000000
start with 1
increment by 1
nocache;缓存序列号,防止系统宕机或者其他情况导致不连续,也可以设置nocache
  • Trigger:
create or replace trigger tri_test
  before insert on TableName   --表名
  for each row
declare
  nextid number;
begin
  IF :new.Id IS NULL or :new.Id=0 THEN --Id是列名,主键
    select Seq_Test.nextval --Seq_Test上面创建的序列号
    into nextid
    from sys.dual;
    :new.Id:=nextid;
  end if;
end tri_test;
  • XML配置
<insert id="add" parameterType="cn.crm.PO">
<selectKey resultType="java.lang.Integer"  order="BEFORE(After)" keyProperty="Id">
SELECT Seq_Test.NEXTVAL FROM DUAL
</selectKey>
insert into system_user (name, parent_id,
phone_num, password, description
)
values (#{name,jdbcType=VARCHAR},
#{parent_id,jdbcType=SMALLINT},
#{phone_num,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR}
)
</insert>

MySql

Mysql自带自增主键,所以只需要XML配置即可,有两种配置方式都行。
第一种:

<insert id="add" parameterType="cn.crm.PO" useGeneratedKeys="true" keyProperty="id">

insert into system_user (name, parent_id,
phone_num, password, description
)
values (#{name,jdbcType=VARCHAR},
#{parent_id,jdbcType=SMALLINT},
#{phone_num,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR}
)

</insert>
插入之后自动封装到PO中,直接PO.getId()就可以拿到

第二种:

<insert id="add" parameterType="cn.crm.PO">
    <selectKey resultType="java.lang.Short" order="AFTER" keyProperty="id">
        SELECT LAST_INSERT_ID() AS id
    </selectKey>
insert into system_user (name, parent_id,
phone_num, password, description
)
values (#{name,jdbcType=VARCHAR},
#{parent_id,jdbcType=SMALLINT},
#{phone_num,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR}
)

</insert>

SqlServer

感觉Mybatis不是很支持SqlServer,配置方式就一种:

<insert id="add" parameterType="cn.crm.PO" useGeneratedKeys="true" keyProperty="id">

insert into system_user (name, parent_id,
phone_num, password, description
)
values (#{name,jdbcType=VARCHAR},
#{parent_id,jdbcType=SMALLINT},
#{phone_num,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR}
)

</insert>
和MySql配置方式是一样的。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值