Nhibernate基本的增删改查实践

1、链接配置

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
 3     <session-factory name="Test">
 4         <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
 5         <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
 6         <property name="connection.connection_string">Server=.;initial catalog=TestNHibernate;User Id=sa;Password=Hello1234</property>
 7         <property name="adonet.batch_size">10</property>
 8         <property name="show_sql">true</property>
 9         <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
10         <property name="use_outer_join">true</property>
11         <property name="command_timeout">60</property>
12         <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
13         <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
14         <mapping assembly="TestDomain" />
15     </session-factory>
16 </hibernate-configuration>
hibernate.cfg.xml

2、构建一个Session管理类,用于管理Session

 1     internal class SessionManager
 2     {
 3         private ISessionFactory _sessionFactory;
 4         public SessionManager()
 5         {
 6             _sessionFactory = GetSessionFactory();
 7         }
 8         private ISessionFactory GetSessionFactory()
 9         {
10             return (new Configuration()).Configure().BuildSessionFactory();
11         }
12         public ISession GetSession()
13         {
14             return _sessionFactory.OpenSession();
15         }
16     }
SessionManager

3、构建仓储基类,以便继承

  1     public class BaseRespository<TEntity>
  2         where TEntity : class,new()
  3     {
  4         protected ISession session;
  5         public ISession Session
  6         {
  7             set
  8             {
  9                 session = value;
 10             }
 11         }
 12 
 13         #region
 14         public BaseRespository()
 15         {
 16             session = (new SessionManager()).GetSession();
 17         }
 18         #endregion
 19 
 20         public void Create(TEntity dto)
 21         {
 22             CreateTransaction(dto);
 23         }
 24 
 25         public int CreateAndReturn(TEntity dto)
 26         {
 27             return CreateTransaction(dto);
 28         }
 29 
 30         public int CreateTransaction(TEntity dto)
 31         {
 32             using (ITransaction tx = session.BeginTransaction())
 33             {
 34                 try
 35                 {
 36                     int newId = (int)session.Save(dto);
 37                     session.Flush();
 38                     tx.Commit();
 39                     return newId;
 40                 }
 41                 catch (HibernateException)
 42                 {
 43                     tx.Rollback();
 44                     throw;
 45                 }
 46             }
 47         }
 48 
 49         public void Update(TEntity dto)
 50         {
 51             session.Update(dto);
 52             session.Flush();
 53         }
 54 
 55         public void SaveOrUpdate(IList<TEntity> dtos)
 56         {
 57             foreach (var c in dtos)
 58             {
 59                 session.SaveOrUpdate(c);
 60             }
 61             session.Flush();
 62         }
 63 
 64         public void Delete(TEntity dto)
 65         {
 66             session.Delete(dto);
 67             session.Flush();
 68         }
 69 
 70         public TEntity GetById(object entityId)
 71         {
 72             return this.session.Get<TEntity>(entityId);
 73         }
 74 
 75         public IList<TEntity> GetListByExample(TEntity entity)
 76         {
 77             return this.session.CreateCriteria(typeof(TEntity))
 78                 .Add(Example.Create(entity)
 79                     .IgnoreCase()
 80                     .EnableLike()
 81                     .SetEscapeCharacter('&')
 82                 ).List<TEntity>();
 83         }
 84 
 85         public IList<TEntity> List()
 86         {
 87             return session.CreateCriteria(typeof(TEntity)).List<TEntity>();
 88         }
 89 
 90         public IList<TEntity> List(params ICriterion[] expression)
 91         {
 92             ICriteria query = session.CreateCriteria(typeof(TEntity));
 93             foreach (ICriterion express in expression)
 94             {
 95                 query.Add(express);
 96             }
 97             return query.List<TEntity>();
 98         }
 99 
100         public IList<TResult> Select<TResult>(Func<TEntity, TResult> express)
101         {
102             return session.CreateCriteria(typeof(TEntity)).List<TEntity>().Select(express).ToList();
103         }
104     }
BaseRespository

4、创建领域实体对象

 1     public class Blogcategory
 2     {
 3         public Blogcategory() { }
 4         public virtual int Cateid { get; set; }
 5         public virtual IList<Blogarticle> Blogarticles { get; set; }
 6         public virtual string Catename { get; set; }
 7         public virtual int Parentid { get; set; }
 8         public virtual int State { get; set; }
 9         public virtual int Sortid { get; set; }
10         public virtual int Articlecount { get; set; }
11         public virtual System.DateTime Createtime { get; set; }
12         public virtual string Note { get; set; }
13     }
Blogcategory
 1     public class Blogarticle
 2     {
 3         public Blogarticle() { }
 4         public virtual int Articleid { get; set; }
 5         public virtual Blogcategory Blogcategory { get; set; }
 6         public virtual IList<Blogcomment> Blogcomments { get; set; }
 7         public virtual IList<Blogdigg> Blogdiggs { get; set; }
 8         public virtual string Title { get; set; }
 9         public virtual string Content { get; set; }
10         public virtual string Description { get; set; }
11         public virtual string Imageurl { get; set; }
12         public virtual string Tag { get; set; }
13         public virtual int Hits { get; set; }
14         public virtual bool Istop { get; set; }
15         public virtual int State { get; set; }
16         public virtual System.Nullable<int> Userid { get; set; }
17         public virtual string Username { get; set; }
18         public virtual string Userip { get; set; }
19         public virtual System.DateTime Createtime { get; set; }
20         public virtual System.DateTime Publishtime { get; set; }
21         public virtual System.DateTime Updatetime { get; set; }
22         public virtual string Note { get; set; }
23     }
Blogarticle
 1     public class Blogcomment
 2     {
 3         public Blogcomment() { }
 4         public virtual int Autoid { get; set; }
 5         public virtual Blogarticle Blogarticle { get; set; }
 6         public virtual string Title { get; set; }
 7         public virtual System.Nullable<int> Userid { get; set; }
 8         public virtual string Username { get; set; }
 9         public virtual string Content { get; set; }
10         public virtual System.DateTime Createtime { get; set; }
11         public virtual string Ip { get; set; }
12         public virtual int State { get; set; }
13         public virtual System.Nullable<int> Verifyuserid { get; set; }
14         public virtual string Verifyuseraccount { get; set; }
15     }
Blogcomment
 1     public class Blogdigg
 2     {
 3         public Blogdigg() { }
 4         public virtual int Autoid { get; set; }
 5         public virtual Blogarticle Blogarticle { get; set; }
 6         public virtual string Diggname { get; set; }
 7         public virtual int Surpporttype { get; set; }
 8         public virtual int State { get; set; }
 9         public virtual string Ip { get; set; }
10         public virtual System.DateTime Createtime { get; set; }
11     }
Blogdigg

5、映射文件配置

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <hibernate-mapping assembly="TestDomain" namespace="TestDomain" xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
 3     <class name="Blogcategory" table="BlogCategory">
 4         <id name="Cateid" column="CateID">
 5             <generator class="native" />
 6         </id>
 7         <property name="Catename" column="CateName" />
 8         <property name="Parentid" column="ParentID" />
 9         <property name="State" column="State" />
10         <property name="Sortid" column="SortID" />
11         <property name="Articlecount" column="ArticleCount" />
12         <property name="Createtime" column="CreateTime" />
13         <property name="Note" column="Note" />
14     </class>
15 </hibernate-mapping>
Blogcategory.hbm.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <hibernate-mapping assembly="TestDomain" namespace="TestDomain" xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
 3   <class name="Blogarticle" table="BlogArticle">
 4     <id name="Articleid" column="ArticleID">
 5         <generator class="native" />
 6     </id>
 7     <many-to-one name="Blogcategory" column="BlogCategory_CateID" />
 8     <property name="Title" column="Title" />
 9     <property name="Content" column="Content" />
10     <property name="Description" column="Description" />
11     <property name="Imageurl" column="ImageUrl" />
12     <property name="Tag" column="Tag" />
13     <property name="Hits" column="Hits" />
14     <property name="Istop" column="IsTop" />
15     <property name="State" column="State" />
16     <property name="Userid" column="UserID" />
17     <property name="Username" column="UserName" />
18     <property name="Userip" column="UserIP" />
19     <property name="Createtime" column="CreateTime" />
20     <property name="Publishtime" column="PublishTime" />
21     <property name="Updatetime" column="UpdateTime" />
22     <property name="Note" column="Note" />
23   </class>
24 </hibernate-mapping>
Blogarticle.hbm.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <hibernate-mapping assembly="TestDomain" namespace="TestDomain" xmlns="urn:nhibernate-mapping-2.2">
 3   <class name="Blogcomment" table="BlogComment" lazy="false" >
 4     <id name="Autoid" column="AutoID">
 5         <generator class="native" />
 6     </id>
 7     <many-to-one name="Blogarticle" column="BlogArticle_ArticleID" />
 8     <property name="Title" column="Title" />
 9     <property name="Userid" column="UserID" />
10     <property name="Username" column="UserName" />
11     <property name="Content" column="Content" />
12     <property name="Createtime" column="CreateTime" />
13     <property name="Ip" column="IP" />
14     <property name="State" column="State" />
15     <property name="Verifyuserid" column="VerifyUserID" />
16     <property name="Verifyuseraccount" column="VerifyUserAccount" />
17   </class>
18 </hibernate-mapping>
Blogcomment.hbm.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <hibernate-mapping assembly="TestDomain" namespace="TestDomain" xmlns="urn:nhibernate-mapping-2.2">
 3   <class name="Blogdigg" table="BlogDigg" lazy="false" >
 4     <id name="Autoid" column="AutoID">
 5         <generator class="native" />
 6     </id>
 7     <many-to-one name="Blogarticle" column="BlogArticle_ArticleID" />
 8     <property name="Diggname" column="DiggName" />
 9     <property name="Surpporttype" column="SurpportType" />
10     <property name="State" column="State" />
11     <property name="Ip" column="IP" />
12     <property name="Createtime" column="CreateTime" />
13   </class>
14 </hibernate-mapping>
Blogdigg.hbm.xml

6、构建仓储类

1     public class BlogCategoryRespository : BaseRespository<Blogcategory>
2     {
3         
4     }
5     public class BlogArticleRespository : BaseRespository<Blogarticle>
6     {
7         
8     }

7、测试

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             BlogCategoryRespository target = new BlogCategoryRespository();
 6             Blogcategory dto = new Blogcategory();
 7 
 8             dto.Catename = "Test" + new Random().Next(100000, 999999).ToString();
 9             dto.Parentid = 0;
10             dto.State = 0;
11             dto.Createtime = DateTime.Now;
12 
13             int newid = target.CreateAndReturn(dto);
14 
15             Blogcategory model = target.GetById(2);
16             if (model != null)
17             {
18                 model.Catename = "newCatename";
19                 target.Update(model);
20             }
21 
22             model = target.GetById(1);
23             if (model != null)
24             {
25                 target.Delete(model);
26             }
27 
28             Console.WriteLine(newid);
29             Console.Read();
30         }
31     }


NHibernate下载地址:

  1. http://sourceforge.net/projects/nhibernate/
  2. http://www.nuget.org/packages/NHibernate/
  3. http://hibernate.org/

NHibernate参考手册:NHibernate.chm.rar

posted @ 2014-09-08 11:21  自然去留  阅读(218)  评论(0编辑  收藏  举报