初使NHibernate
今天学习了下NHibernate,因为以前JavaEE中使用过Hibernate框架,所以上手很快,但其中还是遇到了些问题,这里把经验给大家分享下:
首先是使用Code Smith生成实体类和映射文件
1. 找到映射文件属性中的生成操作,把这个属性改成嵌入的资源;
2. 添加NHibernate的程序集(.DLL),然后就可以写具体方法了,看代码吧
===================NHibernareHelp==========================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Expression;
namespace Demo.DAl
{
#region NHibernareHelp
public class NHibernareHelp
{
private ISessionFactory _sessionFactory;
private ISession _session;
public NHibernareHelp()
{
_sessionFactory = GetSessionFactory();
}
private ISessionFactory GetSessionFactory()
{
return (new Configuration()).Configure().BuildSessionFactory();
}
public ISession GetSession()
{
if (_session == null)
return _sessionFactory.OpenSession();
return _session;
}
}
#endregion
}
===================RoomService==========================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Demo.Models;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Expression;
namespace Demo.DAl
{
public class RoomService
{
private ISession _session;
public RoomService()
{
_session = new NHibernareHelp().GetSession();
}
public IList<Room> GetAllRoom()
{
IList<Room> list = _session.GetNamedQuery("[dbo].[proc_room_query]").List<Room>();
return list;
}
}
}
3. 配置文件
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="NHFactory">
<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;Initial Catalog=hotelManageDB;Integrated Security=SSPI</property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<mapping assembly="Demo.Models"/>
</session-factory>
</hibernate-configuration>