Oracle创建自增序列和触发器

2020-02-24  本文已影响0人  飞奔的阿甘

假设存在一个表 SYS_DEPT,ID字段是主键,要求实现自增

创建自增序列

create sequence SYS_DEPT_ID_SEQ

minvalue 1

start with 1

increment by 1

nocache;

查询用户所有的序列:

select SEQUENCE_OWNER,SEQUENCE_NAME from dba_sequences where sequence_owner='OMT_CMS';

删除指定序列:

DROP SEQUENCE SYS_DEPT_ID_SEQ;

创建触发器

create or replace trigger SYS_DEPT_ID_TRI

before insert on SYS_DEPT for each row

begin

select SYS_DEPT_ID_SEQ.nextval into :new.id from dual;

end;

在Mybatis环境下 insert语句返回id的方式:

@Insert("insert into sys_dept(id,name,sort,parent_id) values (#{sysDept.id,jdbcType=INTEGER},#{sysDept.name,jdbcType=VARCHAR},#{sysDept.sort,jdbcType=INTEGER},#{sysDept.parentId,jdbcType=INTEGER})")

@SelectKey(statement = "select SYS_DEPT_ID_SEQ.nextval as id from dual", keyProperty = "sysDept.id", before = true, resultType = Integer.class)

void insertOne(@Param("sysDept") SysDept sysDept);

在调用dao后获取实体类中的id,而不是在返回结果中获取自增的id:

SysDept sysDept = new SysDept();

BeanUtils.copyProperties(deptDTO, sysDept);

sysDeptMapper.insertOne(sysDept);

deptDTO.setId(sysDept.getId());

上一篇 下一篇

猜你喜欢

热点阅读