创设IBatisNet基础代码

IBatisNet
基础代码包蕴:

1.
IBatisNet
实例配置

一个突出的配备文件如下(具体布置项目的含义见后):

<?xml
version=”1.0″ encoding=”utf-8″?>

<sqlMapConfig
xmlns=”http://ibatis.apache.org/dataMapper
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” >

 

  <!– Rem : If used via a
DataAccess context, properties tag will be ignored

  <properties
resource=”../../database.config”/> –>

  <properties
embedded=”database.config, IBatisNetDemo”/>

  <settings>

    <setting
useStatementNamespaces=”${useStatementNamespaces}”/>

    <setting
cacheModelsEnabled=”true”/>

    <setting
validateSqlMap=”false”/>

  </settings>

 

  <!– Optional if resource
–>

  <providers
embedded=”providers.config,IBatisNetDemo”/>

  <!– ==== SqlClient configuration
=========   –>

  <!– Rem : If used via a
DataAccess context, database tag will be ignored –>

  <database>

    <!– Optional ( default )
–>

    <provider
name=”sqlServer1.1″/>

    <dataSource name=”iBatisNet”
connectionString=”data source=localhost;database=Northwind;user
id=sa;password=;connection reset=false;connection lifetime=5; min pool
size=1; max pool size=50″/>

  </database>

 

  <sqlMaps>

    <!– user via
embedded–>

    <sqlMap
embedded=”Map.SqlClient.Person.xml,IBatisNetDemo”/>

  </sqlMaps>

</sqlMapConfig>

2.
PO(Plain Ordinary Object)

下边是大家作为示例的一个PO:

[Serializable]

    public class Person

    {

        private int id;

        private string
firstName;

        private string lastName;

        private DateTime?
birthDate;

        private double?
weightInKilograms;

        private double?
heightInMeters;

 

        public Person() { }

 

        public int Id

        {

            get { return id; }

            set { id = value; }

        }

 

        public string FirstName

        {

            get { return firstName;
}

            set { firstName = value;
}

        }

 

        public string LastName

        {

            get { return lastName;
}

            set { lastName = value;
}

        }

 

        public DateTime?
BirthDate

        {

            get { return birthDate;
}

            set { birthDate = value;
}

        }

 

        public double?
WeightInKilograms

        {

            get { return
weightInKilograms; }

            set { weightInKilograms =
value; }

        }

 

        public double?
HeightInMeters

        {

            get { return
heightInMeters; }

            set { heightInMeters =
value; }

        }

}

3.映射文本

与Hibernate 不一样。因为急需人工编写SQL 代码,IBatisNet
的映照文件一般采

用手动编写(通过Copy/Paste,手工编制映射文件也并没想象中的麻烦)。

针对地点PO 的照耀代码如下:

<?xml
version=”1.0″ encoding=”utf-8″ ?>

 

<sqlMap
namespace=”Person” xmlns=”http://ibatis.apache.org/mapping

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance
>

 

  <alias>

    <typeAlias alias=”Person”
type=”IBatisNetDemo.Domain.Person,IBatisNetDemo” />

  </alias>

 

  <resultMaps>

    <resultMap id=”SelectAllResult”
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>

 

  <statements>

    <select id=”SelectAllPerson”
resultMap=”SelectAllResult”>

      select

      PER_ID,

      PER_FIRST_NAME,

      PER_LAST_NAME,

      PER_BIRTH_DATE,

      PER_WEIGHT_KG,

      PER_HEIGHT_M

      from PERSON

    </select>

 

    <select id=”SelectByPersonId”
resultClass=”Person” parameterClass=”int”>

      select

      PER_ID,

      PER_FIRST_NAME,

      PER_LAST_NAME,

      PER_BIRTH_DATE,

      PER_WEIGHT_KG,

      PER_HEIGHT_M

      from PERSON

      where PER_ID = #value#

    </select>

   

    <insert id=”InsertPerson”  parameterclass=”Person” >

      <selectKey property=”Id”
type=”post” resultClass=”int”>

        ${selectKey}

      </selectKey> 

      insert into Person

      ( PER_FIRST_NAME,

      PER_LAST_NAME,

      PER_BIRTH_DATE,

      PER_WEIGHT_KG,

      PER_HEIGHT_M)

      values

     
(#FirstName#,#LastName#,#BirthDate#, #WeightInKilograms#,
#HeightInMeters#)

    </insert>

 

    <update id=”UpdatePerson”

                  
parameterclass=”Person”>

      <![CDATA[ update Person
set

      PER_FIRST_NAME
=#FirstName#,

      PER_LAST_NAME
=#LastName#,

      PER_BIRTH_DATE
=#BirthDate#,

     
PER_WEIGHT_KG=#WeightInKilograms#,

     
PER_HEIGHT_M=#HeightInMeters#

      where

      PER_ID = #Id# ]]>

    </update>

 

    <delete id=”DeletePerson”
parameterclass=”Person”>

      delete from Person

      where

      PER_ID = #Id#

    </delete>

 

  </statements>

</sqlMap>

 

从上边的映射文件可以看看,通过<insert>、<delete>、<update>、

<select>七个节点,大家独家定义了针对Person
对象的增删改查操作。在那

多个节点中,我们指定了对应的SQL 语句,以update节点为例:

……

<update
id=” UpdatePerson” ⑴

parameterClass=”Person”>

<![CDATA[⑶

 update Person set ⑷

      PER_FIRST_NAME
=#FirstName#,⑸

      PER_LAST_NAME =#LastName#,

      PER_BIRTH_DATE
=#BirthDate#,

     
PER_WEIGHT_KG=#WeightInKilograms#,

     
PER_HEIGHT_M=#HeightInMeters#

      where

PER_ID
= #Id# ⑺]]>

</update>

……

⑴ ID

点名了操作ID,之后大家得以在代码中通过点名操作id
来施行此节点所定

义的操作,如:

SqlMap.Update(“UpdatePerson”,
person);

ID设定使得在一个配置文件中定义多个同名节点成为可能(多个update节

点,_____以不同id区分)

⑵ parameterClass

点名了操作所需的参数类型,此例中update 操作以

IBatisNetDemo.Domain.Person类型的对象作为参数,目的是将提供的Person

实例更新到数据库。

parameterClass=”Person”中,user为“IBatisNetDemo.Domain.Person”

类的别名,别名可透过typeAlias节点指定,如示例配置文件中的:

<typeAlias
alias=”Person” type=”IBatisNetDemo.Domain.Person,IBatisNetDemo” />⑶
<![CDATA[……]]>

通过<![CDATA[……]]>节点,可以幸免SQL 中与XML
规范相争执的字符对

XML映射文件的合法性造成影响。


执行更新操作的SQL,那里的SQL 即事实上数据库支持的SQL
语句,将由

IBatisNet填入参数后提交数据库执行。

⑸ SQL中所需的用户名参数,“# FirstName
#”在运转期会由传入的Person对象的FirstName

质量填充。

⑹ SQL 中所需的用户性别参数“# LastName
#”,将在运行期由传入的user 对象的

LastName属性填充。


SQL中所需的规范参数“#id#”,将在运行期由传入的Person对象的Person属性

填充。

对此那么些示例,IBatisNet在运转期会读取id
为“UpdatePerson”的update节点

的SQL定义,并调用指定的user对象的对应getter方法获取属性值,并用此

属性值,对SQL中的参数进行填充后提交数据库执行。

此例对应的应用级代码如下,其中演示了IBatisNet SQLMap的骨干选用形式:

private
static SqlMapper sqlMap;

public
BaseService()

{

            Assembly assembly =
Assembly.Load(“IBatisNetDemo”);

            Stream stream =
assembly.GetManifestResourceStream(“IBatisNetDemo.sqlmap.config”);

 

            DomSqlMapBuilder builder =
new DomSqlMapBuilder();

            sqlMap = builder.Configure(
stream );

 

 };

个中,SqlMapper是IbatisNet运作的中央,所有的操作均通过SqlMapper实例达成。那些例子中自己将富有的安插文件依照资源文件措施存放,所以从程序集去加载sqlmap.config文件。

可以看到,对于应用层而言,程序员面对的是传统意义上的实体(数据)对象,而不是ADO.NET中的Data里德r或者DataTable/DataSet,那使得大家决定最终的数据操作情势,通过Sql的优化来得到最佳的数据库执行听从,那在依靠SQL自动生成的“全自动”ORM机制中是难以完毕的。

事例代码 http://files.cnblogs.com/shanyou/IBatisNet.rar

未雨绸缪工作

1.       下载ibatis软件包(http://ibatis.apache.org/dotnetdownloads.html)。

2.       创立测试数据库,并在数据库中开创一个Person
表,其中涵盖三个字段:

Name              Type            Size

PER_ID            Long Integer      4   not null

PER_FIRST_NAME    nvarchar         40  not null

PER_LAST_NAME     nvarchar           40  not null

PER_BIRTH_DATE  
 DateTime         8

PER_WEIGHT_KG     float            8

PER_HEIGHT_M      float            8

3.
为了在开发进程更是直观,大家须求将ibatisnet日志打开以便观望ibatinets运作的底细。

ibatisnet选用IBatisNet.Common.Logging.Log4Net,就是利用Log4Net纪录日志的卷入。在Web.config中扩张下边的计划内容:

<configSections>

         <sectionGroup
name=”iBATIS”>

              <section
name=”logging”
type=”IBatisNet.Common.Logging.ConfigurationSectionHandler,
IBatisNet.Common” />

         </sectionGroup>

         <section
name=”log4net”
type=”log4net.Config.Log4NetConfigurationSectionHandler,
log4net” />

</configSections>

<iBATIS>

         <logging>                       

              <logFactoryAdapter
type=”IBatisNet.Common.Logging.Impl.Log4NetLoggerFA,
IBatisNet.Common.Logging.Log4Net”>

                   <arg
key=”configType”
value=”inline”
/>

                   <arg key
=”showLogName” value=”true” />

                   <arg key
=”showDataTime” value=”true” />

                   <arg key
=”level” value=”ALL” />

                   <arg key
=”dateTimeFormat” value=”yyyy/MM/dd HH:mm:ss:SSS” />

              </logFactoryAdapter>                

         </logging>

     </iBATIS>

     <!–
This section contains the log4net configuration settings –>

     <log4net>

         <!–
Define some output appenders –>

         <appender
name=”RollingLogFileAppender” type=”log4net.Appender.RollingFileAppender”>

              <param
name=”File” value=”log.txt”
/>

              <param
name=”AppendToFile”
value=”true” />

              <param
name=”MaxSizeRollBackups”
value=”2″ />

              <param
name=”MaximumFileSize”
value=”100KB”
/>

              <param
name=”RollingStyle”
value=”Size” />

              <param
name=”StaticLogFileName”
value=”true” />

              <layout
type=”log4net.Layout.PatternLayout”>

                   <param
name=”Header”
value=”[Header]\r\n”
/>

                   <param
name=”Footer”
value=”[Footer]\r\n”
/>

                   <param
name=”ConversionPattern”
value=”%d [%t] %-5p %c
[%x] – %m%n” />

              </layout>

         </appender>

                   <appender
name=”ConsoleAppender”
type=”log4net.Appender.ConsoleAppender”>

              <layout
type=”log4net.Layout.PatternLayout”>

                   <param
name=”ConversionPattern”
value=”%d [%t] %-5p %c
[%x] <%X{auth}> –
%m%n” />

              </layout>

         </appender>       

         <!–
Set root logger level to ERROR and its appenders –>

         <root>

              <level
value=”DEBUG”
/>

              <appender-ref
ref=”RollingLogFileAppender” />

              <appender-ref
ref=”ConsoleAppender”
/>

         </root>

        

         <!–
Print only messages of level DEBUG or above in the packages –>

         <logger
name=”IBatisNet.DataMapper.Configuration.Cache.CacheModel”>

              <level
value=”DEBUG”
/>

         </logger>

         <logger
name=”IBatisNet.DataMapper.Configuration.Statements.PreparedStatementFactory”>

              <level
value=”DEBUG”
/>

         </logger>

         <logger
name=”IBatisNet.DataMapper.LazyLoadList”>

              <level
value=”DEBUG”
/>

         </logger>

         <logger
name=”IBatisNet.DataAccess.DaoSession”>

              <level
value=”DEBUG”
/>

         </logger>

         <logger
name=”IBatisNet.DataMapper.SqlMapSession”>

              <level
value=”DEBUG”
/>

         </logger>

         <logger
name=”IBatisNet.Common.Transaction.TransactionScope”>

              <level
value=”DEBUG”
/>

         </logger>

         <logger
name=”IBatisNet.DataAccess.Configuration.DaoProxy”>

              <level
value=”DEBUG”
/>

         </logger>

     </log4net>

        

 

相关文章

网站地图xml地图