轉自:https://www.cnblogs.com/panie2015/p/5807683.html
Mybatis 操作數據庫的主鍵自增長
本篇文章將研究mybatis 實現oracle主鍵自增的機制
首先我們看對於同一張student表,對於mysql,sql server,oracle中它們都是怎樣創建主鍵的
在mysql中
|
1
2
3
4
5
6
7
|
create table Student(
Student_ID
int
(
6
) NOT NULL PRIMARY KEY AUTO_INCREMENT,
Student_Name varchar(
10
) NOT NULL,
Student_Age
int
(
2
) NOT NULL
);
insert into student(student_name,student_age) values(
'zhangsan'
,
20
);
|
在sql server中
|
1
2
3
4
5
6
|
create table Student(
Student_ID
int
primary key identity(
1
,
1
),
Student_Name varchar2(
10
) NOT NULL,
Student_Age number(
2
) NOT NULL
);
insert into student(student_name,student_age) values(
'zhangsan'
,
20
);
|
在oracle中
|
1
2
3
4
5
|
create table Student(
Student_ID number(
6
) NOT NULL PRIMARY KEY,
Student_Name varchar2(
10
) NOT NULL,
Student_Age number(
2
) NOT NULL
);
|
而oracle如果想設置主鍵自增長,則需要創建序列
|
1
2
3
4
5
6
7
|
CREATE SEQUENCE student_sequence
INCREMENT BY
1
NOMAXVALUE
NOCYCLE
CACHE
10
;
insert into Student values(student_sequence.nextval,
'aa'
,
20
);
|
如果使用了觸發器的話,就更簡單了
|
1
2
3
4
5
6
7
|
create or replace trigger student_trigger
before insert on student
for
each row
begin
select student_sequence.nextval into :
new
.student_id from dual;
end student_trigger;
/
|
此時插入的時候觸發器會幫你插入id
|
1
|
insert into student(student_name,student_age) values(
'wangwu'
,
20
);
|
至此,mysql,sql server,oracle中怎樣創建表中的自增長主鍵都已完成。
看一看出oracle的主鍵自增較mysql和sql sever要復雜些,mysql,sqlserver配置好主鍵之后,插入時,字段和值一一對應即可,數據庫就會完成你想做的,但是在oracle由於多了序列的概念,如果不使用觸發器,oracle怎樣實現主鍵自增呢?
|
1
2
3
4
5
6
|
<insert id=
"add"
parameterType=
"Student"
>
<selectKey keyProperty=
"student_id"
resultType=
"int"
order=
"BEFORE"
>
select student_sequence.nextval from dual
</selectKey>
insert into student(student_id,student_name,student_age) values(#{student_id},#{student_name},#{student_age})
</insert>
|
或者
|
1
2
3
4
5
6
|
<insert id=
"save"
parameterType=
"com.threeti.to.ZoneTO"
>
<selectKey resultType=
"java.lang.Long"
keyProperty=
"id"
order=
"AFTER"
>
SELECT SEQ_ZONE.CURRVAL AS id from dual
</selectKey>
insert into TBL_ZONE (ID, NAME ) values (SEQ_ZONE.NEXTVAL, #{name,jdbcType=VARCHAR})
</insert>
|
MyBatis 插入時候獲取自增主鍵方法有二
以MySQL5.5為例:
方法1:
|
1
2
3
|
<insert id=
"insert"
parameterType=
"Person"
useGeneratedKeys=
"true"
keyProperty=
"id"
>
insert into person(name,pswd) values(#{name},#{pswd})
</insert>
|
方法2:
|
1
2
3
4
5
6
|
<insert id=
"insert"
parameterType=
"Person"
>
<selectKey keyProperty=
"id"
resultType=
"long"
>
select LAST_INSERT_ID()
</selectKey>
insert into person(name,pswd) values(#{name},#{pswd})
</insert>
|
