Ibatis中insert用法

时间:2024-02-20 18:37:55

在Ibatis中,insert()的返回值为一个Object的主键,其实这个Object的主键是这样的来的:如果在bean的xml文件中设置了插入的keyProperty,则insert()方法返回的就是这个主键的值。

    例如,所以我们想要在插入时想要插入一个sequence值到数据库的某个字段(当然,这个字段的类型为Number的),我们可以在xml文件中做如下配置(以下为在DB服务器是Oracle的前提下):

<insert id="insertUser" parameterClass="po.User">
     <selectKey resultClass="int" keyProperty="userId" >
         SELECT user_account_s.nextval AS userid FROM dual
     </selectKey>
  insert into user_account(userid, username, password, groupname)
          values(#userId#, #userName#, #password#, #groupName#)
 </insert>

此时插入到数据库中的某表userid字段的值即使sequence的值。但要注意的是,配置中出现的红色加粗字体一定要对应到bean中的属性字段,也即要与bean中的属性字段名称相同,否则则会抛出异常。

如果是SQL SERVER数据库,则进行如下配置:

 

<insert id="insertUser" parameterClass="po.User">
    insert into user_account(userid, username, password, groupname)
          values(#userId#, #userName#, #password#, #groupName#)
     <selectKey resultClass="int" keyProperty="userId" >
         SELECT @@IDENTITY as userid
     </selectKey>
 </insert>

 如果是MYSQL 数据库,则进行如下配置:

<insert id="MS-SYS-SEQ-INSERT">
     <![CDATA[
         insert into sys_seq(name) values (#name#)
     ]]>
     <selectKey resultClass="long" keyProperty="id">
         <![CDATA[SELECT LAST_INSERT_ID() AS ID ]]>
     </selectKey>
    </insert>

关于Ibatis insert后返回值为null,ibatis的api文档是这样写的解释的: 

关于com.ibatis.sqlmap.client.SqlMapExecutor下的insert (java.lang.String id, java.lang.Object parameterObject) 方法,

Executes a mapped SQL INSERT statement. Insert is a bit different from other update methods, as it provides facilities for returning the primary key of the newly inserted row (rather than the effected rows). This functionality is of course optional. 

The parameter object is generally used to supply the input data for the INSERT values. 

Parameters: 
id - The name of the statement to execute. 
parameterObject - The parameter object (e.g. JavaBean, Map, XML etc.). 
Returns: 
The primary key of the newly inserted row. This might be automatically generated by the RDBMS, or selected from a sequence table or other source. 
Throws: 
java.sql.SQLException - If an error occurs. 


它的意思是说返回值是新插入记录的主键,类型为Object主要是因为主键类型可以是int也可以是String类型。 

然而,如果我们使用下列的配置文件进行插入的话,返回的值为null 

Xml代码 

<insert id="insertPrdcategory" parameterClass="Prdcategory"> 
insert into Prdcategory ( name,pid,deep ) values ( #name#, 
#pid#, #deep# ) 
</insert>