Ibatis.net Introduction

Source: Internet
Author: User

Ibatis.net Introduction

Ibatis.net is an open source project launched in 2001, it is a lightweight ORM framework, now Ibatisnet is a sub-project under Apache, the latest version is 1.6.2.

Official website: http://www.mybatis.org/

. NET project: http://code.google.com/p/mybatisnet/

Datamapper: The XML business object that is mapped by configuring the mapping relationship with SQL statements and stored procedures.

Dataacces: The Ibatis data access layer is a simple thing to say.

Ibatis.net Configuration

A few of the main configuration files to use:

Providers.config this direct copy to the root directory, which defines the various database drivers, including SQL Server, Oracle, MySQL, PostgreSQL, DB2 and OLE DB, ODBC, etc.

Sqlmap.config is a very central configuration file that is primarily configured with database access strings, settings settings, and the configuration of entity classes and database table-related XML.

There is also a database.config file that is configured with some parameters that are used in the Sqlmap.

Then you need to introduce two DLL files.

Sqlmap.config File Code:

<?xml version= "1.0" encoding= "Utf-8"?>
<sqlmapconfig xmlns= "Http://ibatis.apache.org/dataMapper" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" >
  <!--<providers resource= "Database.config"/>-->
  <settings>
    <setting usestatementnamespaces= "true"/>
    <setting cachemodelsenabled= "true"/>
  </settings>
  <providers resource= "Providers.config"/>
  <database>
    <!--Optional (default)--
    <provider name= "sqlServer2.0"/>
    <datasource name= "ibatisnet" connectionstring= "server=.; User Id=sa; Password=sa;database=testdb; Persist Security info=true "/>
    </database>
  <sqlMaps>
    <sqlmap resource= "Maps/account.xml"/>
  </sqlMaps>
</sqlMapConfig>

Usestatementnamespaces: Whether the namespace is enabled

Cachemodelsenabled: whether to cache data

<providers resource= "Providers.config"/> Introduction of database driver files

The Sqlmaps node is an XML file that configures some SQL statements and entity mappings.

Ibatis.net Combat

Now let's do a demo

I'm using Sqlserver2005, a new data sheet.

Create a new project under Vs2010 Ibatisdemo

The project structure is as follows

Ibatisdemo.dao provides a unified mapper access interface,

Ibatisdemo.model Data Entity

Ibatisdemo.service Data manipulation

Because the demo does not have too much detail set for the overall architecture.

First configure the Maps/account.xml under the root directory of the Web site as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<sqlmap namespace= "Account" xmlns= "http://ibatis.apache.org/mapping" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance ">
  <alias>
    <!--alias: Take aliases
                    Assembly: Represents the file where the class resides
                    Type: Represents the full name of the class
      -
    <typealias alias= "Account" assembly= "IBatisDemo.Model.dll" type= "IBatisDemo.Model.Accounts"/>
  </alias>
  <resultMaps>
    <resultmap id= "Account-result"  class= "Account" >
      <result property= "id"    column= "id"/>
      <result property= "Item"    column= "item"/>
      <result property= "Year",    column= "year"/>
      <result property= "Month"    column= "Month"/>
      <result property= "Day"    column= "Day"/>
      <result property= "Createon"    column= "Createon"/>
      <result property= "level"    column= "level"/>
    </resultMap>
  </resultMaps>
  <statements>
    <select id= "Sql_selectbyid" resultmap= "Account-result" >
      SELECT * FROM Accounts
      <dynamic prepend= "where" >
        <isparameterpresent property= "id" prepend= "" >
          [id] = #id #
        </isParameterPresent>
      </dynamic>
    </select>
    <select id= "Sql_selectall" resultmap= "Account-result" >
      SELECT * FROM Accounts
    </select>
    <insert id= "Sql_insertone" parameterclass= "Account" >
      Insert into Accounts (item,money,year,month,day,createon,level)
      Values
      (#Item #,
      #Money #,
      #Year #,
      #Month #,
      #Day #,
      #CreateOn #,
      #Level #
      )
      <selectkey  type= "POST" resultclass= "int" property= "Id" >
        SELECT CAST (@ @IDENTITY as int) as Id
      </selectKey>
    </insert>
  </statements>
</sqlMap>

Description

Statements node:

Some of the commonly used properties in these container labels are as follows

Resultmap and ResultClass comparison:

1,Resultmap belongs to the direct mapping, you can set the result set of the database field and the entity class in the attribute one by one corresponding, so that the results obtained by the SELECT statement will be accurate on the number

2,ResultClass belongs to stealth mapping, although you specify resultclass= "", a specific class, but the result of the SELECT statement is a strength record, but if the database field and the Class property name inconsistent, this time there will be a mapping error , one way to solve this is to give each field the same name as the property with the as operator when writing the SELECT statement: for example: Select Realname as Name ... Where Realname is the field column name, name is the property field name

3, Resultmap than ResultClass performance is higher. Try to use Resultmap

The Selectkey under the Insert label is the primary key ID that returns the data you just inserted, as described below

<!--in order for the insert operation to return the ID of the inserted record, you must write an selectkey–> for the insert
<!--here's how SQL Server is written--
    <selectkey  type= "POST" resultclass= "int" property= "Id" >
      SELECT CAST (@ @IDENTITY as int) as Id
    </selectKey>
    The following is the syntax for Oracle, which is not autoincrement, but is implemented with triggers
    Currval is defined in the trigger.
-
<!--<insert id= "Insertremark" parameterclass= "Remarkinfo" >
    Insert into Sgs_remark (REMARK) VALUES (#remark #)
    
     
    
</insert>
-
<!--Here's how to do it for MySQL---
    
    
    </selectKey>

Account.xml configuration complete. Build entity class:

Using System;
Using System.Collections.Generic;
Using System.Text;
Namespace Ibatisdemo.model
{
    public class Accounts
    {
        public int Id {get; set;}
        public string Item {get; set;}
        Public float Money {get; set;}
        public int Month {get; set;}
        public int year {get; set;}
        public int day {get; set;}
        Public DateTime Createon {get; set;}
        public string level {get; set;}
    }
}

Mapper.cs gets the object class for Mapper:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using Ibatisnet.datamapper;
Using IBatisNet.Common.Utilities;
Using IBatisNet.DataMapper.Configuration;
Namespace Ibatisdemo.dao
{
    public class Mapper
    {
        private static volatile isqlmapper _mapper = null;
        protected static void Configure (Object obj)
        {
            _mapper = null;
        }
        protected static void Initmapper ()
        {
            Configurehandler handler = new Configurehandler (Configure);
            Domsqlmapbuilder builder = new Domsqlmapbuilder ();
            _mapper = Builder. Configureandwatch (handler);
        }
        public static Isqlmapper Instance ()
        {
            if (_mapper = = null)
            {
                Lock (typeof (Sqlmapper))
                {
                    if (_mapper = = null)//Double-check
                    {
                        Initmapper ();
                    }
                }
            }
            return _mapper;
        }
        public static Isqlmapper Get ()
        {
            return Instance ();
        }
        <summary>
        Realmarket Mapper
        </summary>
        public static Isqlmapper Getmaper
        {
            Get
            {
                if (_mapper = = null)
                {
                    Lock (typeof (Isqlmapper))
                    {
                        if (_mapper = = null)
                        {
                            Configurehandler hander = new Configurehandler (Configure);
                            Domsqlmapbuilder builder = new Domsqlmapbuilder ();
                            _mapper = Builder. Configureandwatch ("Sqlmap.config", hander);
                        }
                    }
                }
                return _mapper;
            }
        }
    }
}

And then build AccountService.cs data access inside the service.

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Reflection;
Using System.IO;
Using Ibatisdemo.model;
Using System.Data.SqlClient;
Using Ibatisdemo.dao;
Namespace Ibatisdemo.service
{
    public class Accountservice
    {
        public int Testinsertone (Accounts account)
        
            Object obj =mapper.getmaper.insert ("Account.sql_insertone", account);
            return (int) obj;
        }
        Public Accounts getaccount (int id)
        {
            Return (Accounts) Mapper.GetMaper.QueryForObject ("Account.sql_selectbyid", id);
        }
        
        {
            Return mapper.getmaper.queryforlist<accounts> ("Account.sql_selectall", null);
        }
    }
}

Notice the namespace here.

Invoking the service on the Default.aspx page

protected void Button1_Click (object sender, EventArgs e)
      {
          Accounts account = new Accounts ();
          Account. Id =-1;
          Account. Createon = DateTime.Now;
          Account. Day = 12;
          Account. Item = "small just 1";
          Account. Level = "None";
          Account. Money = 56;
          Account. Month = 6;
          Account. Year = 2011;
          Accountservice service = new Accountservice ();
          Service. Testinsertone (account);
      }
      protected void Button3_Click (object sender, EventArgs e)
      {
          Accountservice service = new Accountservice ();
          ilist<accounts> Accounts = service. Getaccountlist ();
          This. Gridview1.datasource = accounts;
          This. Gridview1.databind ();
      }
      protected void button2_click (object sender, EventArgs e)
      {
          Accountservice service = new Accountservice ();
          Accounts account = Service. Getaccount (2);
      }

Operating effect:

Ibatis.net Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.