IBatis学习
(1)建立
SqlMap.config文件
<?xml version="1.0" encoding="utf-8" ?>
<sqlMapConfig
xmlns="http://ibatis.apache.org/dataMapper"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!--<properties resource="SqlMap.properties"/>-->
<settings>
<setting useStatementNamespaces="false"/>
<setting cacheModelsEnabled="false"/>
</settings>
<!--<providers embedded="WHTR.PPMoney.DaoCfg.providers.config, WHTR.PPMoney.DaoCfg" />-->
<providers resource="providers.config"/>
<database>
<provider name="sqlServer2005"/>
<dataSource name="pp" connectionString="server=192.168.1.2;database=DB1;user id=sa;password=123"/>
</database>
<sqlMaps>
<sqlMap resource="Person.xml"/>
</sqlMaps>
</sqlMapConfig>
(2) 建立 Person.xml
<?xml version="1.0" encoding="utf-8" ?>
<!--<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">-->
<sqlMap namespace="" xmlns="http://ibatis.apache.org/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<alias>
<typeAlias alias="Person" type="Ibatis.PersonModel"/>
</alias>
<statements>
<select id="selectAllPerson" resultClass="Person">
select top 1 * from
Person
</select>
<insert id="insertPerson">
insert into Person(name)
values(#name#)
<selectKey property="Id" resultClass="int" type="post">
select value = @@IDentity
</selectKey>
</insert>
</statements>
</sqlMap>
(3)建立 PersonModel类
namespace Ibatis
{
public class PersonModel
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
}
(4) 建立Dao
public class BaseDao
{
public static ISqlMapper _sqlMap = null;
static BaseDao()
{
_sqlMap = Mapper.Instance();
}
}
public class PersonDao : BaseDao
{
public IList<PersonModel> GetList()
{
ISqlMapper mapper = _sqlMap;
IList<PersonModel> ListPerson = mapper.QueryForList<PersonModel>("selectAllPerson", null); //这个"SelectAllPerson"就是xml映射文件的Id
return ListPerson;
}
public int AddPerson(PersonModel person)
{
Hashtable ht = new Hashtable();
ht.Add("name",person.Name);
object o = _sqlMap.Insert("insertPerson", ht);
return Convert.ToInt16(o);
}
}
(5) 使用方法
class Program
{
static void Main(string[] args)
{
var person=new PersonModel(){Name="zhang"};
PersonDao dao = new PersonDao();
int id= dao.AddPerson(person);
IList<PersonModel> ListPerson = dao.GetList();
foreach (PersonModel p in ListPerson)
{
Console.WriteLine(p.Id + p.Name);
}
Console.ReadKey();
}
}