在mybatis插件oracle數據庫,如果是主鍵自增型的,就要考慮是已經有觸發器處理,還是隻有sequence,這樣才能在保存後的類裏面主鍵纔有值。
1、只有sequence時,demo如下
declare
V_NUM number;
BEGIN
V_NUM := 0;
----判斷序列是否存在(區分大小寫)
select count(0) into V_NUM from user_sequences where sequence_name=upper('S_SYS_USER');
----如果存在立即刪除
if V_NUM > 0 then
execute immediate 'DROP SEQUENCE S_SYS_USER';
end if;
END;
/
--創建序號的規則
create sequence S_SYS_USER
INCREMENT BY 1 -- 每次加幾個
START WITH 1 -- 從1開始計數
NOMAXVALUE -- 不設置最大值
NOCYCLE ; -- 一直累加,不循環
/
<insert id="save" parameterType="com.bootdo.system.domain.UserDO">
<selectKey resultType="long" keyProperty="userId" order="BEFORE">
SELECT S_SYS_USER.NEXTVAL FROM DUAL
</selectKey>
insert into sys_user
(
username,
name,
password,
)
values
(
#{username,jdbcType=VARCHAR},
#{name,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR}
)
</insert>
2、通過Oracle觸發器
declare
V_NUM number;
BEGIN
V_NUM := 0;
----判斷序列是否存在(區分大小寫)
select count(0) into V_NUM from user_sequences where sequence_name=upper('S_SYS_USER');
----如果存在立即刪除
if V_NUM > 0 then
execute immediate 'DROP SEQUENCE S_SYS_USER';
end if;
END;
/
--創建序號的規則
create sequence S_SYS_USER
INCREMENT BY 1 -- 每次加幾個
START WITH 1 -- 從1開始計數
NOMAXVALUE -- 不設置最大值
NOCYCLE ; -- 一直累加,不循環
/
--創建觸發器 DROP TRIGGER TIB_SYS_USER --刪除觸發器
create or replace trigger TIB_SYS_USER before insert on SYS_USER for each row
declare
integrity_error exception;
errno integer;
errmsg char(200);
dummy integer;
found boolean;
begin
select S_SYS_USER.NEXTVAL INTO :new.user_id from dual;
exception
when integrity_error then
raise_application_error(errno, errmsg);
end;
<insert id="save" parameterType="com.bootdo.system.domain.UserDO">
<selectKey resultType="long" keyProperty="userId" order="AFTER">
SELECT S_SYS_USER.CURRVAL FROM DUAL
</selectKey>
insert into sys_user
(
username,
name,
password
)
values
(
#{username,jdbcType=VARCHAR},
#{name,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR}
)
</insert>
@Transactional
@Override
public int save(UserDO user) {
int count = userMapper.save(user);
//這樣userid纔能有值
Long userId = user.getUserId();
return count;
}