1.ssh框架:
hibernate反向生成实体类中映射文件一般如下:
<id name="basiNo" type="java.lang.Long">
<column name="BASI_NO" precision="10" scale="0"/>
<generator class="sequence" />
</id>
oracle中添加自增序列:
-- Create sequence
create sequence BASI_SEQ
minvalue 1
maxvalue 999999999999999999999999999
start with 61
increment by 1
cache 20;
然后在映射文件中修改如下:
BASI_SEQ为oracle中设置的自增序列名。
<id name="basiNo" type="java.lang.Long">
<column name="BASI_NO" precision="10" scale="0" />
<generator class="sequence" >
<param name="sequence">BASI_SEQ</param>
</generator>
</id>
在service中实现添加方法时不用理会主键,会自行增加。
2.ssm框架
通过在oracle中创建主键自增触发器来完成。
如下表:
-- Create table
create table TEST
(
ID NUMBER(16) not null,
QUESTION VARCHAR2(100),
ANSWER VARCHAR2(4000),
FLAG NUMBER(8)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table TEST
add constraint TEST_PK primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
创建自增序列:
-- Create sequence
create sequence TEST_SEQ
minvalue 1
maxvalue 9999999999999999999999999999
start with 23
increment by 1
cache 20;
添加触发器:
create or replace trigger test_trigger
before insert on test
for each row
begin
select test_seq.nextval into :new.id from dual;
mapping.xml文件中增加语句如下:
<insert id="insert" parameterType="com.bean.entity.Test" useGeneratedKeys="true" flushCache="true">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
<!-- <selectKey keyProperty="id" resultType="java.lang.Long" order="BEFORE">
select max(id)+1 from TEST
</selectKey> -->
insert into TEST
(QUESTION, ANSWER,FLAG)
values
(#{question,jdbcType=VARCHAR},#{answer,jdbcType=VARCHAR},#{flag,jdbcType=DECIMAL})
</insert>
以上就完成了ssm框架中对主键自增的处理。