myBatis 新增数据并返回ID
1、注解方式 Mapper 类需要注意的 statement 是获取 下一个ID 的方法before 代表是在插入语句之前执行,还是之后执行oracle before = truemysql、sqlservice before=falsemysql 数据库@InsertProvider
@InsertProvider(type = CUDTemplate.class, method = "save")
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Long.class)
void saveSearch(Search search);
@InsertProvider(type = CUDTemplate.class, method = "save")
@SelectKey(statement="SELECT @@IDENTITY", keyProperty="N_ID", before=false, resultType=Long.class)
void saveChart(Chart chart);
@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);
public class GenerationType {
//mysql
public static final String AUTO = "auto";
//oracle
public static final String SEQUENCE = "sequence";
//mysql and oracle
public static final String UUID = "uuid";
}
@Id(name="n_id")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
我们在数据库插入一条数据的时候,经常是需要返回插入这条数据的主键。但是数据库供应商之间生成主键的方式都不一样。
有些是预先生成(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为表名称
更多推荐
所有评论(0)