create table dectuser(
?????????? userid integer primary key,? /*主键,自动增加*/
?????????? name varchar2(20),
????????? ?sex varchar2(2)
?????????? );2、创建自动增长序列
????? drop sequence dectuser_tb_seq;
????? create sequence dectuser_tb_seq minvalue 1 maxvalue 99999999
?????????????? increment by 1
?????????????? start with 1;?? /*步长为1*/
?
<insert id="insert" parameterClass="cn.javass.spring.chapter7.UserModel">?
??? <selectKey resultClass="int" type="pre" keyProperty="id" >?
???????? SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL?
??? </selectKey>?
???? insert into test (id,name) values (#irrd#,#myName#)?
</insert>
?
在进行数据的插入时,有的业务需要获得相应的生成的主键值,以下是ibatis的实现方式:
有些数据库是预生成(pre-generate)主键的,如Oracle和PostgreSQL;有些是后生成(post-generate)主键的,如MySQL和SQL Server。不管是哪种方式,都可以用iBATIS的<selectkey>节点来获取<insert>语句所产生的主键。
demo如下:
- <!-- Oracle SEQUENCE Example using .NET 1.1 System.Data.OracleClient -->??
- <insert?id="insertProduct-ORACLE"?parameterClass="product">??
- ????<selectKey?resultClass="int"?type="pre"?keyProperty="id"?>??
- ???????? SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL??
- ????</selectKey>??
- ???? insert into PRODUCT (PRD_ID,PRD_DESCRIPTION) values (#id#,#description#)??
- </insert>??
- ??
- <!-- Microsoft SQL Server IDENTITY Column Example -->??
- <insert?id="insertProduct-MS-SQL"?parameterClass="product">??
- ???? insert into PRODUCT (PRD_DESCRIPTION)??
- ???? values (#description#)??
- ????<selectKey?resultClass="int"?typ