NHibernate的入门
.Net下使用orm的话一般会采用EntityFrameWork微软自己家的,小的话其实也会采用Linq To Sql.当然NHibernate也是挺不错的,在Java下这么有名的框架,今天拿来试用下。
新建一测试项目ntest,项目需要引用Iesi.Collections.dll,NHibernate.dll这两个dll,我们可以通过NuGet安装。
使用NHibernate需要进行配置,建立配置文件hibernate.cfg.xml,配置内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=localhost;user=sa;password=123;Initial Catalog=test</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping assembly="ntest"/>
</session-factory>
</hibernate-configuration>
其中一段配置内容
<mapping assembly="ntest"/>
是很重要的,这是我们实体类的命名空间,NHibernate会从该命名空间中查找实体类以及同名的.hbm.xml的实体映射文件
然后我们建立实体类Emp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ntest
{
public class Emp
{
public virtual string empid { get; set; }
public virtual string empname { get; set; }
public virtual int age { get; set; }
public virtual string depid { get; set; }
public virtual string tel { get; set; }
}
}
继续建立该实体类的映射文件.hbm.xml形式的Emp.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="ntest" namespace="ntest" default-lazy="false">
<class name="Emp" table="Emp">
<id name="empid">
<column name="empid" sql-type="varchar" not-null="true" />
</id>
<property name="empname" column="empname"/>
<property name="age" column="age"/>
<property name="depid" column="depid"/>
<property name="tel" column="tel"/>
</class>
</hibernate-mapping>
测试代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate;
using NHibernate.Cfg;
namespace ntest
{
class Program
{
static void Main(string[] args)
{
var cfg = new Configuration();
cfg.Configure(AppDomain.CurrentDomain.BaseDirectory + "\\hibernate.cfg.xml");
ISessionFactory sessionFactory = cfg.BuildSessionFactory();
ISession session = sessionFactory.OpenSession();
try
{
Emp emp = new Emp();
emp.empid = "002";
emp.empname = "jhon";
emp.age = 25;
emp.empid = "123";
emp.tel = "123";
var obj = session.Save(emp);
session.Flush();
}
catch (Exception e)
{
throw e.InnerException;
}
}
}
}
这样一个简单的通过NHibernate来操作数据库的例子就完成了啊,更多功能还需要后续使用中发现。