您的位置:首页 > 数据库 > Oracle

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

2018-01-06 21:31 741 查看

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配置方式是一样的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息