mybatis如何实现序列自增长

mybatis如何实现序列自增长,第1张

一、首先我们看对于同一张student表,对于mysql,sql server,oracle中它们都是怎样创建主键的

1、在mysql中

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)

2、在sql server中

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)

3、在oracle中

create table Student(

Student_ID number(6) NOT NULL PRIMARY KEY,

Student_Name varchar2(10) NOT NULL,

Student_Age number(2) NOT NULL

)

而oracle如果想设置主键自增长,则需要创建序列

CREATE SEQUENCE student_sequence

INCREMENT BY 1

NOMAXVALUE

NOCYCLE

CACHE 10

insert into Student values(student_sequence.nextval,'aa',20)

如果使用了触发器的话,就更简单了

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

insert into student(student_name,student_age) values('wangwu',20)

至此,mysql,sql server,oracle中怎样创建表中的自增长主键都已完成。

看一看出oracle的主键自增较mysql和sql sever要复杂些,mysql,sqlserver配置好主键之后,插入时,字段和值一一对应即可,数据库就会完成你想做的,但是在oracle由于多了序列的概念,如果不使用触发器,oracle怎样实现主键自增呢?

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

或者

<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:

<insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="id">

insert into person(name,pswd) values(#{name},#{pswd})

</insert> 

方法2:

<insert id="insert" parameterType="Person">

<selectKey keyProperty="id" resultType="long">

select LAST_INSERT_ID()

</selectKey>

insert into person(name,pswd) values(#{name},#{pswd})

</insert>

插入前实体id属性为0;

插入后实体id属性为保存后自增的id;

设置主键自增,应该是设置具体的数据库,与mybatis没有什么关系吧。

以mysql为例,假设主键为id

1.可以在创建表的时候设置主键

create table tb (

id bigint(20) primary key auto_increment

)

2.也可以在修改表结构的时候设置主键

alter table tb

modify id bigint(20) primary key auto_increment

更多请参考http://blog.lifw.org/post/35110918

另外在自增的主键在mybatis中可以这么获取

<insert id="..." useGeneratedKeys="true" keyProperty="id">

...

</insert>

create or replace trigger tri_table

before insert on table

for each row

begin

:new.id :=seq_table.nextval

end

/


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11548951.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-16
下一篇2023-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存