Oracle创建自增序列和触发器

假设存在一个表 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());

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容