myBatis 新增資料並返回ID
@InsertProvider(type =CUDTemplate.class, method ="save")
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Long. class)
void saveSearch(Search search);
sqlservice 資料庫
@InsertProvider(type =CUDTemplate.class, method ="save")
@SelectKey(statement="SELECT @@IDENTITY", keyProperty="N_ID", before=false, resultType=Long.class)
void saveChart(Chart chart);
oracle 資料庫@InsertProvider(type =CUDTemplate.class, method ="save")
@SelectKey(statement="SELECT DDS_SEQ.nextval AS ID FROM DUAL", keyProperty="id", before=true, resultType=Long.class)
void saveNews(News news);
domain 實體類需要注意的
publicclassGenerationType{
//mysql
publicstaticfinalString AUTO ="auto";
//oracle
publicstaticfinalString SEQUENCE ="sequence";
//mysql and oracle
publicstaticfinalString UUID ="uuid";
}
@Id(name="n_id")
@GeneratedValue(strategy =GenerationType.AUTO)
publicLong getId(){
return id;
}
2、xml配置方式
我們在資料庫插入一條資料的時候,經常是需要返回插入這條資料的主鍵。但是資料庫供應商之間生成主鍵的方式都不一樣。
有些是預先生成(pre-generate)主鍵的,如Oracle和PostgreSQL;有些是事後生成(post-generate)主鍵的,如MySQL和SQL Server。但不管是哪種方式,我們都可以用ibatis的節點來獲取語句所產生的主鍵。
oracle例子:
<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>
sql-server例子:
<insert id="insertProduct-MS-SQL" parameterClass="product">
insert into PRODUCT (PRD_DESCRIPTION) values (#description#)
<selectKey resultClass="int" type="post" keyProperty="id" >
select @@IDENTITY as value
</selectKey>
</insert>
mysql例子:
<insert id="insertProduct-MYSQL" parameterClass="product">
insert into PRODUCT (PRD_DESCRIPTION) values (#description#)
<selectKey resultClass="int" type="post" keyProperty="id" >
select LAST_INSERT_ID() as value
</selectKey>
</insert>
SQLite例子:
<insert id="Create" parameterClass="Subject">
INSERT INTO SUBJECT
(SubjectName,QuestionCount,IsNowPaper)
VALUES(#SubjectName#,#QuestionCount#,#IsNowPaper#)
<selectKey resultClass="int" type="post" property="SubjectId">
SELECT seq
FROM sqlite_sequence
WHERE (name = 'SUBJECT')
</selectKey>
</insert>
注意:name = 'SUBJECT'中SUBJECT為表名稱