配置文件调优
NHibernate v1.0 官方 Demo 中是用xml格式进行配置映射的
官方还提供了其他方式,下面介绍其中一种[NHibernate.Mapping.Attributes]属性映射
在官方文档 v5.2的第28章有详细介绍
开始
- 创建一个新的项目
- 安装NHibernate nuget包
- 安装NHibernate.Mapping.Attributes nuget包
- 数据库表结构
Column | Type | Modifiers
--------+--------------+----------------------
CatId | char(32) | not null, primary key
Name | nvarchar(16) | not null
Sex | nchar(1) |
Weight | real |
- 创建一个Cat映射类,并标记属性
[Class(Table = "Cat")]
public class Cat
{
[Id(0, TypeType = typeof(string), Column = "CatId", Generator = "uuid.hex")]
public virtual string Id { get; set; }
[Property(Column = "Name")]
public virtual string Name { get; set; }
[Property(Column = "Sex")]
public virtual char Sex { get; set; }
[Property(Column = "Weight")]
public virtual float Weight { get; set; }
}
- 创建NHibernateHelper类
public sealed class NHibernateHelper
{
private const string CurrentSessionKey = "nhibernate.current_session";
private static readonly ISessionFactory _sessionFactory;
static NHibernateHelper()
{
_sessionFactory = GetSessionFactory();
}
public static ISessionFactory GetSessionFactory()
{
var configuration = new Configuration();
configuration.DataBaseIntegration(c =>
{
c.Dialect<MsSql2012Dialect>();
c.ConnectionString = @"Server=localhost\SQLEXPRESS;initial catalog=quickstart;Integrated Security=True";
});
// Enable validation (optional)
HbmSerializer.Default.Validate = true;
// Here, we serialize all decorated classes (but you can also do it class by class)
configuration.AddInputStream(HbmSerializer.Default.Serialize(Assembly.GetExecutingAssembly()));
return configuration.BuildSessionFactory();
}
public static ISession GetCurrentSession()
{
var context = HttpContext.Current;
var currentSession = context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
currentSession = _sessionFactory.OpenSession();
context.Items[CurrentSessionKey] = currentSession;
}
return currentSession;
}
public static void CloseSession()
{
var context = HttpContext.Current;
var currentSession = context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
// No current session
return;
}
currentSession.Close();
context.Items.Remove(CurrentSessionKey);
}
public static void CloseSessionFactory()
{
if (_sessionFactory != null)
{
_sessionFactory.Close();
}
}
}
- 运行后查看数据库数据是否插入成功
- 您觉得与v1.0版本比,您更喜欢哪种呢?
- 至此一个最基本的nhiberate使用方法介绍完毕,往后扩展的代码都会在v2.0版本的基础上