NHibernate 3.2 GA 正式版于 2011-07-30 发布,这一版本对 CodeFirst 的支持性更好了,因为它提供了 Conformist 取代之前第三方的 ConfOrm。
NHibernate 3.2 下载地址:http://sourceforge.net/projects/nhibernate/files/NHibernate/
下面将讲一下如何使用这一新成员进行数据库的基本操作。我使用的开发环境是:VS2010 + NHibernate 3.2 + MVC 3,下面是项目目录图:
项目只要引用 “Iesi.Collections.dll” 和 “NHibernate.dll” 两个类库文件即可。
NHibernateCfg 代码:
注意,“MsSql2005Dialect” 表示使用SQL 2005数据库,数据库名为“DiPiPiDB”。
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using NHibernate.Cfg;
- using NHibernate.Dialect;
- using NHibernate.Driver;
- using NHibernate.Mapping.ByCode;
- namespace DiPiPi.Mvc3.Orm
- {
- public static class NHibernateCfg
- {
- private const string _ConnectionString =
- @"Data Source=localhost;Initial Catalog=DiPiPiDB;Integrated Security=True;Pooling=False";
- public static Configuration GetConfiguration()
- {
- var configure = new Configuration();
- configure.SessionFactoryName("DiPiPiDB");
- configure.DataBaseIntegration(db =>
- {
- db.Dialect<MsSql2005Dialect>();
- db.Driver<SqlClientDriver>();
- db.ConnectionString = _ConnectionString;
- });
ISessionManager 代码:
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using NHibernate;
- namespace DiPiPi.Mvc3.Orm
- {
- public interface ISessionManager
- {
- ISessionFactory GetSession();
- void CreateDataTable();
- void DropDataTable();
- }
SessionManager 代码:
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using NHibernate;
- using NHibernate.Cfg;
- using NHibernate.Cfg.MappingSchema;
- using NHibernate.Tool.hbm2ddl;
- using NHibernate.Mapping.ByCode;
- namespace DiPiPi.Mvc3.Orm
- {
- /// <summary>
- /// 使用 NHibernate 操作数据库的Session
- /// </summary>
- public class SessionManager : ISessionManager
- {
- private Configuration conf = null;
- private ISessionFactory sessionFactory = null;
- private ModelMapper mapper = null;
- public SessionManager()
- {
- mapper = new ModelMapper();
- conf = NHibernateCfg.GetConfiguration();
- LoadOrmMapping();
- }
- public Configuration GetConfiguration()
- {
- return conf;
- }
- private void LoadOrmMapping()
- {
- //在Configuration中添加HbmMapping
- AddMapping<UserInfoMap>();
- var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
- conf.AddMapping(hbmMapping);
- //Console.WriteLine(hbmMapping.AsString());
- }
- private void AddMapping<TModel>() where TModel : IConformistHoldersProvider, new()
- {
- mapper.AddMapping<TModel>();
- }
- public ISessionFactory GetSession()
- {
- //配置数据库
- SchemaMetadataUpdater.QuoteTableAndColumns(conf);
- //建立SessionFactory
- sessionFactory = conf.BuildSessionFactory();
- return sessionFactory;
- }
- public void CreateDataTable()
- {
- //配置数据库
- SchemaMetadataUpdater.QuoteTableAndColumns(conf);
- //创建数据库
- new SchemaExport(conf).Create(false, true);
- }
- public void DropDataTable()
- {
- //配置数据库
- SchemaMetadataUpdater.QuoteTableAndColumns(conf);
- //删除数据库
- new SchemaExport(conf).Drop(false, true);
- }
- public ISession OpenSession()
- {
- if (sessionFactory != null)
- {
- return sessionFactory.OpenSession();
- }
- else
- {
- return null;
- }
- }
- public void CloseSession()
- {
- if (sessionFactory != null)
- {
- sessionFactory.Close();
- }
- }
- }
- }
UserInfo 实体类代码:
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace DiPiPi.Mvc3.Orm
- {
- public class UserInfo
- {
- public virtual int UserId { get; set; }
- public virtual string UserName { get; set; }
- }
- }
UserInfoMap 实体映射类代码:
注意,这里开始使用 Conformist 了,“Generators.Identity”表示主键为整型自增,如果是“Generators.Guid” 表示采用Guid方式,还有其他方式,大家可以去研究。
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using NHibernate.Mapping.ByCode;
- using NHibernate.Mapping.ByCode.Conformist;
- namespace DiPiPi.Mvc3.Orm
- {
- /// <summary>
- /// http://taven.cnblogs.com
- /// 李锡远的博客
- /// 实体映射类
- /// </summary>
- public class UserInfoMap : ClassMapping<UserInfo>
- {
- public UserInfoMap()
- {
- Id(entity => entity.UserId, map =>
- {
- map.Column("UserInfoID");
- map.Generator(Generators.Identity);
- });
- Property(entity => entity.UserName, map => map.Length(150));
UserInfoRepository 数据库读取的仓储类代码:(这个类包含了数据库的 增、删、改 常用方法)
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using NHibernate.Criterion;
- namespace DiPiPi.Mvc3.Orm
- {
- public class UserInfoRepository
- {
- private ISessionManager sessionManage;
- public UserInfoRepository(ISessionManager _sessionManage)
- {
- sessionManage = _sessionManage;
- }
- public List<UserInfo> FindAll()
- {
- using (var session = sessionManage.GetSession().OpenSession())
- {
- var query = session.QueryOver<UserInfo>()
- .OrderBy(p => p.UserId).Asc
- .List();
- return query.ToList();
- }
- }
- public List<UserInfo> Find(ICriterion condition)
- {
- using (var session = sessionManage.GetSession().OpenSession())
- {
- var query = session.QueryOver<UserInfo>()
- .Where(condition)
- .OrderBy(p => p.UserId).Asc
- .List();
- return query.ToList();
- }
- }
- public List<UserInfo> FindbyExample(UserInfo entity)
- {
- using (var session = sessionManage.GetSession().OpenSession())
- {
- var query = session.CreateCriteria<UserInfo>().Add(Example.Create(entity)).List<UserInfo>();
- return query.ToList();
- }
- }
- public void Save(UserInfo model)
- {
- using (var session = sessionManage.GetSession().OpenSession())
- {
- using (var trans = session.BeginTransaction())
- {
- session.Save(model);
- trans.Commit();
- }
- }
- }
- public void Modify(UserInfo model)
- {
- using (var session = sessionManage.GetSession().OpenSession())
- {
- using (var trans = session.BeginTransaction())
- {
- session.Update(model);
- trans.Commit();
- }
- }
- }
- public void Remove(UserInfo entity)
- {
- using (var session = sessionManage.GetSession().OpenSession())
- {
- using (var trans = session.BeginTransaction())
- {
- session.Delete(entity);
- trans.Commit();
- }
- }
- }
- public void RemoveByID(int Id)
- {
- using (var session = sessionManage.GetSession().OpenSession())
- {
- using (var trans = session.BeginTransaction())
- {
- session.CreateQuery("delete UserInfo where UserId = :userId").SetInt32("userId", Id).ExecuteUpdate();
- trans.Commit();
- }
- }
- }
- public void Removes(String userName
将实体代码写好后,执行下面代码可直接创建数据库的表:
Code Snippet
- ISessionManager session = new SessionManager();
- session.CreateDataTable();
执行下面代码可插入数据:
Code Snippet
- ISessionManager session = new SessionManager();
- UserInfoRepository userinfoR = new UserInfoRepository(session);
- for (var i = 0; i < 10; i++)
- {
- UserInfo u = new UserInfo();
- u.UserName = "+i;远哥"
- userinfoR.Save(u);
- }
执行下面代码可读取数据:
- ISessionManager session = new SessionManager();
- UserInfoRepository userinfoR = new UserInfoRepository(session);
- List<UserInfo> list = userinfoR.FindAll();
项目源码打包下载:http://files.cnblogs.com/taven/DiPiPiDemo.rar