IBatisNet 之 自动生成主关键字

时间:2022-04-23
本文章向大家介绍IBatisNet 之 自动生成主关键字,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

很多系统支持自动生成主关键字。一些数据库厂商预先生成(oracle),一些数据库厂商之后生成(mssal mysql).。如果你在<insert>元素中使用<selectKey>节,你就能获得一个预先生成的key.。下面的例子演示了这种方法:

<!—Oracle SEQUENCE Example --> <insert id="insertProduct-ORACLE"        parameterClass="product">       <selectKey resultClass="int"       Property="id" > SELECT STOCKIDSEQUENCE.NEXTVAL AS ID 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"         Property="id" > SELECT @@IDENTITY AS ID </selectKey>         </insert>

上面是IbatisNet的iBATIS Data Mapper Developer Guide上的说明:下面来介绍一下具体的应用和注意的地方: person.xml


?xml version="1.0" encoding="utf-8" ?> 
<sqlMap 
 namespace="Person" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:noNamespaceSchemaLocation="SqlMap.xsd"> 
 <!-- XML "behind" document for the People service class. -->
 <alias> 
  <typeAlias alias="Person" type="IbatisTest.Domain.Person, IbatisTest.Domain" /> 
 </alias> 
 
 <resultMaps> 
  <resultMap id="SelectResult" class="Person"> 
   <result property="Id" column="PER_ID" /> 
   <result property="FirstName" column="PER_FIRST_NAME" /> 
   <result property="LastName" column="PER_LAST_NAME" /> 
   <result property="BirthDate" column="PER_BIRTH_DATE" /> 
   <result property="WeightInKilograms" column="PER_WEIGHT_KG" /> 
   <result property="HeightInMeters" column="PER_HEIGHT_M" /> 
  </resultMap> 
 </resultMaps> 
 
  <insert id="Insert" parameterClass="Person"> 
   insert into PERSON 
    (PER_FIRST_NAME, PER_LAST_NAME, 
    PER_BIRTH_DATE, PER_WEIGHT_KG, PER_HEIGHT_M) 
   values 
    ( #FirstName#, #LastName#, 
    #BirthDate#, #WeightInKilograms#, #HeightInMeters#) 
   <selectKey property="Id" type="post" resultClass="int">  
   select CAST(@@IDENTITY as int) as value 
   </selectKey>  
  </insert>     
   </statements> 
 
</sqlMap>  
<selectKey>节返回一个从sql server生成的自动生成关键字。 
 //新增一个员工 
 private void Button1_Click(object sender, System.EventArgs e) 
          { 
 IbatisTest.Domain.Person person = new IbatisTest.Domain.Person(); 
  person.Id =-1;//这里的赋值很重要,否则会出错
              person.FirstName = "--New Person--"; 
 person.BirthDate = Convert.ToDateTime("2000-4-2");  
 PersonHelper personhelper = new PersonHelper(); 
  personhelper.Insert(person); 
 } 

          //业务逻辑类方法
          public int Insert (Person person) 
          {
  try
              { 
  int result = -1; 
   result =(int)Mapper().Insert("Insert",person); 
  return result; 
 }
  catch(Exception ex) 
 { 
  throw ex; 
 } 
 }