MyBatis. Net configuration, mybatis.net Configuration

Source: Internet
Author: User

MyBatis. Net configuration, mybatis.net Configuration

If we have such a requirement, we need to manage student information.

The student table must meet the following requirements:

Field name

Data Type

Description

StuNo

Character

Student ID. This column is required. It is an incremental primary key.

StuName

Character

Student name. This column is required. The last name may contain two characters, for example, Ouyang junxiong.

     

StuSex

Character

Student gender. This column is required and can only be "male" or "female ". Because there are many boys, the default value is "male"

StuAge

Number

Student age. This column is required and must be in the range of 15 to 15 ~ Between 50 years old

StuSeat

Number

Student seat number

StuAddress

Character

Student address. This column can be left blank. If not, the default value is "unknown address"

 

1 .-Create a table [student_tb]

Create table student_tb (StuNo int identity () primary key, StuName varchar (10) not null, StuSex varchar (5) check (StuSex in ('male', 'female ')) default ('male'), StuAge int check (StuAge between 15 and 50) not null, StuSeat int not null, StuAddress varchar (20) default ('address unknown '),);

2 .-Create entity

public class StudentInfo    {        public int StuNo { get; set; }        public string StuName { get; set; }        public string StuSex { get; set; }        public int StuAge { get; set; }        public int StuSeat { get; set; }        public string StuAddress { get; set; }    }

3 .-CreateSqlMapper Provider

You can create SqlMapper in the following ways:

A. method 1

ISqlMapper _ sqlMapper = IBatisNet. DataMapper. Mapper. Instance ()

Note:Requirements for this methodSqlMap. configThe file is located in the application root directory, and the file name is and is only"SqlMap. config".

B. method 2

ISqlMapper _ sqlMapper = new DomSqlMapBuilder (). Configure ()

Note: Same as above

C. Method 3-specify the path of SqlMap. config (when you use EmbededResource to find the config resource, SqlMap. config is required to generate the operation attributeEmbedded Resources)

XmlDocument sqlMapConfig = Resources. GetEmbeddedResourceAsXmlDocument ("Config. SqlMap. config, Persistence ");

ISqlMapper _ sqlMapper = new DomSqlMapBuilder (). Configure (sqlMapConfig); // --- the third

The MyBatisProvider code is as follows:

Public class MyBatisProvider {private static ISqlMapper _ sqlMapper; private static object sysncObj = new object (); public static ISqlMapper GetInstanse () {if (_ sqlMapper = null) {lock (sysncObj) {if (_ sqlMapper = null) {// _ sqlMapper = IBatisNet. dataMapper. mapper. instance (); // --- type 1 // _ sqlMapper = new DomSqlMapBuilder (). configure (); // --- the second XmlDocument sqlMapConfig = Resources. getEmbeddedResourceAsXmlDocument ("MyBatis. sqlMap. config, MyBatis "); _ sqlMapper = new DomSqlMapBuilder (). configure (sqlMapConfig); // --- Type 3 }}return _ sqlMapper ;}}

4.-In the project

Add configuration file

A. provider. config

Search for images on the Internet.

<?xml version="1.0" encoding="utf-8"?><providersxmlns="http://ibatis.apache.org/providers"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  <clear/>  <provider   name="sqlServer4.0"   enabled="true"   description="Microsoft SQL Server, provider V4.0.0.0 in framework .NET V4.0"   assemblyName="System.Data, Version=4.0.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089"   connectionClass="System.Data.SqlClient.SqlConnection"   commandClass="System.Data.SqlClient.SqlCommand"   parameterClass="System.Data.SqlClient.SqlParameter"   parameterDbTypeClass="System.Data.SqlDbType"   parameterDbTypeProperty="SqlDbType"   dataAdapterClass="System.Data.SqlClient.SqlDataAdapter"   commandBuilderClass=" System.Data.SqlClient.SqlCommandBuilder"   usePositionalParameters = "false"   useParameterPrefixInSql = "true"   useParameterPrefixInParameter = "true"   parameterPrefix="@"   allowMARS="false"    /></providers>

B. SqlMap. config

<? Xml version = "1.0" encoding = "UTF-8"?> <SqlMapConfig xmlns = "http://ibatis.apache.org/dataMapper" xmlns: <settings> <setting useStatementNamespaces = "true"/> <setting cacheModelsEnabled = "true"/> </settings> <providers embedded = "MyBatis. providers. config, myBatis "/> <database> <provider name =" sqlServer4.0 "/> <dataSource name =" dataSourceName "connectionString =" connection statement "/> </database> <sqlMaps> <sqlMap embedded = "MyBatis. sqlMaps. studentInfo. xml, MyBatis "/> </sqlMaps> </sqlMapConfig>

Select different locations and names based on the instance creation method in the code.

Note: <setting useStatementNamespaces = "true"/> true indicates that statementName must use Namespace, that is, the namespace attribute in the object ing XML.

Ing XML file paths to entities under the sqlMaps Node

Embedded indicates that the file property generation operation is an embedded resource.

5.-create an object ing File

<?xml version="1.0" encoding="utf-8" ?><sqlMap namespace="StudentInfo" xmlns="http://ibatis.apache.org/mapping"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  <alias>    <typeAlias alias="StudentInfo" type="Model.StudentInfo,Model" />  </alias>  <resultMaps>    <resultMap id="StudentResult" class="StudentInfo">      <result property="StuNo" column="stuNo"/>      <result property="StuName" column="stuName"/>      <result property="StuSex" column="stuSex"/>      <result property="StuAge" column="stuAge"/>      <result property="StuSeat" column="stuSeat"/>      <result property="StuAddress" column="stuAddress"/>    </resultMap>  </resultMaps>  <statements>    <insert id="Insert" parameterClass="StudentInfo" resultClass="int">      INSERT INTO [student_tb]([stuName],[stuSex],[stuAge],[stuSeat],[stuAddress])      VALUES(#StuName#,#StuSex#,#StuAge#,#StuSeat#,#StuAddress#)      <selectKey property="StuNo" resultClass="int" type="post" >        SELECT @@identity AS StuNo      </selectKey>    </insert>    <delete id="Delete" parameterClass="Int32">      UPDATE [student_tb]      SET [stuName] = #StuName#,[stuSex] = #StuSex#,[stuAge] = #StuAge#,[stuSeat] = #StuSeat#,[stuAddress] = #StuAddress#      WHERE [stuNo]=#StuNo#    </delete>    <update id="Update" parameterClass="StudentInfo">      UPDATE [student_tb]      SET [stuName] = #StuName#,[stuSex] = #StuSex#,[stuAge] = #StuAge#,[stuSeat] = #StuSeat#,[stuAddress] = #StuAddress#      WHERE [stuNo]=#StuNo#    </update>        <select id="Get" parameterClass="Int32" resultMap="StudentResult">      select * from [student_tb] where stuNo=#StuNo#    </select>        <select id="List" parameterClass="map" resultMap="StudentResult">      select * from [student_tb]    </select>  </statements></sqlMap>

As shown above, it is a simple XML Entity ing file.

Use the resultMaps node to map object attributes to database fields. In statements, add, delete, modify, query, and other related operation nodes and SQL

6.-DAL database operations

public class StudentDAL    {        public int Insert(StudentInfo info)        {            string stmtName = "StudentInfo.Insert";            return Convert.ToInt32(MyBatisProvider.GetInstanse().Insert(stmtName, info) ?? "0");        }        public int Update(StudentInfo info)        {            string stmtName = "StudentInfo.Update";            return MyBatisProvider.GetInstanse().Update(stmtName, info);        }        public StudentInfo Get(int id)        {            string stmtName = "StudentInfo.Get";            return MyBatisProvider.GetInstanse().QueryForObject<StudentInfo>(stmtName, id);        }        public IList<StudentInfo> List()        {            string stmtName = "StudentInfo.List";            return MyBatisProvider.GetInstanse().QueryForList<StudentInfo>(stmtName, null);        }    }

Sample Code:


Mybatis configuration attributes

Class Blog {
String aa;
List <Comment> comments;

}

<ResultMap type = "Blog" id = "BlogResult">
<Id column = "id" property = "id"/>
<Collection property = "comments" column = "id" ofType = "Comment" javaType = "java. util. ArrayList" select = "selectCommentsByBlogId"> </collection>
</ResultMap>

<Select id = "selectBlog" parameterType = "int" resultMap = "BlogResult">
<! [CDATA [select * from t_blog where id = # {id}]>
</Select>

Please refer to this example

How to configure the mybatis ing File

I recommend you to write blog.csdn.net/...924701

Related Article

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.