Fluent NHibernate and Spring.net

http://blog.bennymichielsen.be/2009/01/04/using-fluent-nhibernate-in-spring-net/

http://comments.gmane.org/gmane.comp.windows.dotnet.nhibernate.user.general/21840

http://codegur.com/2049968/configuring-asp-net-mvc-2-with-spring-net-and-fluentnhibernate

SQL:

1
2
3
4
5
6
7
8
9
10
11
12
13
CREATE TABLE StaffManager
(
    ManagerId INT IDENTITY(1,1) PRIMARY KEY,
    ManagerStaffIdKey INT FOREIGN KEY
                REFERENCES StaffMember(StaffId),   --职员ID 外键
    ManagerIs BIT DEFAULT(1),                       --账号是否有效
    ManagerName NVARCHAR(50) NOT NULL,              --登录账号
    ManagerPassWord VARCHAR(50) NOT NULL,           --密码
    ManagerMail VARCHAR(100) NOT NULL,              --找回密码邮箱
    ManagerDate DATETIME DEFAULT(GETDATE())
    --管理人员ID 外键
)
GO

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Data.NHibernate; //4.0
using NHibernate.Cfg;
using FluentNHibernate.Automapping;
using FluentNHibernate.Conventions.Helpers;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using System.Reflection;
using FluentNHibernate;
using NHibernate.Tool.hbm2ddl;
using NHibernate;
 
namespace BasicProject.NHibernateInfra.Implementation {
    public class FluentNhibernateLocalSessionFactoryObject : LocalSessionFactoryObject{
        ///// <summary>
        ///// Sets the assemblies to load that contain fluent nhibernate mappings.
        ///// </summary>
        ///// <value>The mapping assemblies.</value>
        //public string[] FluentNhibernateMappingAssemblies {
        //    get;
        //    set;
        //}
 
        public string[] FluentNhibernateMappingAssemblies { get; set; }
        public string ConnectionStringName { get; set; }
        static readonly object factorylock = new object();
 
        protected override void PostProcessConfiguration(Configuration config) {
            ConnectionStringName = "Server=geovindu;Database=geovindu;User ID=root;Password=geovindu";
            base.PostProcessConfiguration(config);
            FluentConfiguration fluentConfig = Fluently.Configure(config)
                .Database(MySQLConfiguration.Standard.ConnectionString(ConnectionStringName))
                .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true));
 
            Array.ForEach(FluentNhibernateMappingAssemblies,
                           assembly => fluentConfig.Mappings(
                                                    m => m.FluentMappings.AddFromAssembly(Assembly.Load(assembly))
                                                        .Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultLazy.Never())
                                                    )
                         );
            fluentConfig.BuildSessionFactory();
        }
    } //class
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Text;
using System.Collections.Generic;
using NHibernate.Validator.Constraints;
 
 
namespace Domain.Entities {
     
    public class StaffManager {
        public StaffManager() {
            CardCancellations = new List<CardCancellation>();
            CardRecords = new List<CardRecord>();
            JobRightsAssignments = new List<JobRightsAssignment>();
            StaffManagerLogs = new List<StaffManagerLog>();
            StaffUserChecks = new List<StaffUserCheck>();
            ViolateRegulations = new List<ViolateRegulation>();
        }
        public virtual int ManagerId { get; set; }
        public virtual StaffMember StaffMember { get; set; }
        public virtual bool? ManagerIs { get; set; }
        [NotNullNotEmpty]
        [Length(50)]
        public virtual string ManagerName { get; set; }
        [NotNullNotEmpty]
        [Length(50)]
        public virtual string ManagerPassWord { get; set; }
        [NotNullNotEmpty]
        [Length(100)]
        public virtual string ManagerMail { get; set; }
        public virtual DateTime? ManagerDate { get; set; }
        public virtual IList<CardCancellation> CardCancellations { get; set; }
        public virtual IList<CardRecord> CardRecords { get; set; }
        public virtual IList<JobRightsAssignment> JobRightsAssignments { get; set; }
        public virtual IList<StaffManagerLog> StaffManagerLogs { get; set; }
        public virtual IList<StaffUserCheck> StaffUserChecks { get; set; }
        public virtual IList<ViolateRegulation> ViolateRegulations { get; set; }
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Collections.Generic;
using System.Text;
using FluentNHibernate.Mapping;
using Domain.Entities;
 
namespace Domain.Mappings {
     
    /// <summary>
    ///
    /// </summary>
    public class StaffManagerMap : ClassMap<StaffManager> {
         
        public StaffManagerMap() {
            Table("StaffManager");
            LazyLoad();
            Id(x => x.ManagerId).GeneratedBy.Identity().Column("ManagerId");
            References(x => x.StaffMember).Column("ManagerStaffIdKey");
            Map(x => x.ManagerIs).Column("ManagerIs");
            Map(x => x.ManagerName).Column("ManagerName").Not.Nullable().Length(50);
            Map(x => x.ManagerPassWord).Column("ManagerPassWord").Not.Nullable().Length(50);
            Map(x => x.ManagerMail).Column("ManagerMail").Not.Nullable().Length(100);
            Map(x => x.ManagerDate).Column("ManagerDate");
            HasMany(x => x.CardCancellations).KeyColumn("CancelManagerIdKey");
            HasMany(x => x.CardRecords).KeyColumn("CardManagerIdKey");
            HasMany(x => x.JobRightsAssignments).KeyColumn("RightsManagerIdKey");
            HasMany(x => x.StaffManagerLogs).KeyColumn("ManagerIdKey");
            HasMany(x => x.StaffUserChecks).KeyColumn("CheckManagerIdKey");
            HasMany(x => x.ViolateRegulations).KeyColumn("ViolateManagerIdKey");
        }
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public abstract class Repository<T> : ILongKeyedRepository<T> where T : class{
       private ISessionFactory sessionFactory;
       /// <summary>
       /// Session factory for sub-classes.
       /// </summary>
       public ISessionFactory SessionFactory {
           protected get { return sessionFactory; }
           set { sessionFactory = value; }
       }
 
       /// <summary>
       /// Get's the current active session. Will retrieve session as managed by the
       /// Open Session In View module if enabled.
       /// </summary>
       public ISession CurrentSession {
           get { return SessionFactory.GetCurrentSession(); }
       }
 
 
       public T FindBy(long id) {
           return CurrentSession.Get<T>(id);
       }
 
       public IQueryable<T> All() {
           return CurrentSession.Query<T>();
       }
 
       public T FindBy(System.Linq.Expressions.Expression<Func<T, bool>> expression) {
           throw new NotImplementedException();
       }
 
       public IQueryable<T> FilterBy(System.Linq.Expressions.Expression<Func<T, bool>> expression) {
           return All().Where(expression).AsQueryable();
       }
 
       public void Add(T entity) {
           CurrentSession.Save(entity);
       }
 
       public void Add(IEnumerable<T> entities) {
           foreach (var entity in entities) {
               CurrentSession.Save(entity);   
           }
       }
 
       public void Update(T entity) {
           CurrentSession.Update(entity);
       }
 
       public void Delete(T entity) {
           CurrentSession.Delete(entity);
       }
 
       public void Delete(IEnumerable<T> entities) {
           foreach (var entity in entities) {
               CurrentSession.Save(entity);
           }
       }
   } //end class

  

 

1
2
3
public class StaffManagerRepository : Repository<StaffManager> {
 
} /

  Web.config:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<spring>
  <context>
    <resource uri="~/Config/objects.xml"/>
     
    <!-- 嵌入在程序集中的配置文件 ,首先是程序集名称,然后命名空间,最后文件名, 注意名称的大小写必须完全一致 -->
    <resource uri="assembly://geovindu.Dao/geovindu.Dao.Config/dataAccess.xml"/>
    <resource uri="assembly://geovindu.Dao/geovindu.Dao.Config/objects.xml"/>
    <resource uri="assembly://geovindu.Service/geovindu.Service.Config/objects.xml"/>
  </context>
   
  <!--数据库配置服务器地址-->
  <databaseSettings>
    <add key="db.server" value="LF-WEN\GEOVINDU"/>
    <add key="db.database" value="TSQLFundamentals2008"/>
    <add key="db.userid" value="sa"/>
    <add key="db.password" value="7888888"/>
  </databaseSettings>
</spring>

  

1
objects.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  <object id="SessionFactory" type="geovindu.NHibernateInfra.Implementation.FluentNhibernateLocalSessionFactoryObject, geovindu.NHibernateInfra.Implementation">
      <!--<property name="DbProvider" ref="DbProvider"/>-->
      <property name="ConnectionStringName" value="MysqlConnection"/>
      <property name="ExposeTransactionAwareSessionFactory" value="true" />
      <property name="FluentNhibernateMappingAssemblies">
          <list>
              <value>geovindu.NHibernateInfra.Implementation</value>
          </list>
      </property>
      <property name="HibernateProperties">
          <dictionary>
              <entry key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
              <!--<entry key="dialect" value="NHibernate.Dialect.MsSql2008Dialect"/>
              <entry key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>-->
              <!--<entry key="current_session_context_class" value="Spring.Data.NHibernate.SpringSessionContext, Spring.Data.NHibernate33"/>-->
              <entry key="cache.use_second_level_cache" value="true" />
              <entry key="cache.provider_class"
                        value="NHibernate.Cache.HashtableCacheProvider,NHibernate" />
              <entry key="max_fetch_depth" value="0" />
          </dictionary>
      </property>
 
      <property name="ExposeTransactionAwareSessionFactory" value="true" />
  </object>
 
 
<!-- Transaction Management Strategy - local database transactions -->
<object id="transactionManager"
      type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate33">
  <property name="DbProvider" ref="DbProvider"/>
  <property name="SessionFactory" ref="SessionFactory"/>
</object>

  

1
DAO:objects.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  <!-- NHibernate 配置 涂聚文 Geovin Du -->
 
<!-- 可以通过 name 为其指定别名 name="SessionFactory" -->
  <object id="NHibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject,Spring.Data.NHibernate4">
     <!--关于数据库连接的配置,直接使用 DbProvider 中的设置,这样,不需要为 Hibernate 再提供连接串和驱动-->
    <property name="DbProvider" ref="DbProvider"/>
     <!--包含有映射文件的程序集,需要分析的hbm程序集名称-->
    <property name="MappingAssemblies">
      <list>
        <value>Domain</value>
      </list>
    </property>
     <!--其他的参数-->
    <property name="HibernateProperties">
      <dictionary>
         <!--方言-->
        <entry key="dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
        <entry key="use_proxy_validator" value="false" />
        <entry key="show_sql" value="true"/>
      </dictionary>
    </property>
     <!--必须增加此项说明,与 Spring 的声明式事务集成-->
    <property name="ExposeTransactionAwareSessionFactory" value="true" />
  </object>
 
 
 
 
  <!-- Fluent NHibernate 配置  涂聚文 Geovin Du-->
 
    <!-- 可以通过 name 为其指定别名 name="SessionFactory" -->
    <object id="NHibernateSessionFactory" type="Geovin.Du.Domain.FluentNhibernateLocalSessionFactoryObject, Domain">
        <!--关于数据库连接的配置,直接使用 DbProvider 中的设置,这样,不需要为 Hibernate 再提供连接串和驱动-->
        <property name="DbProvider" ref="DbProvider"/>
        <!--包含有映射文件的程序集,需要分析的Mappings程序集名称-->
        <property name="FluentNhibernateMappingAssemblies">
            <list>
                <value>Domain</value>
            </list>
        </property>
        <!--其他的参数-->
        <property name="HibernateProperties">
            <dictionary>
                <!--方言-->
                <entry key="dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
                <entry key="use_proxy_validator" value="false" />
                <entry key="show_sql" value="true"/>
            </dictionary>
        </property>
        <!--必须增加此项说明,与 Spring 的声明式事务集成-->
        <property name="ExposeTransactionAwareSessionFactory" value="true" />
    </object>

  

 

posted @   ®Geovin Du Dream Park™  阅读(490)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2011-04-21 C# 获取Windows语言类型(两种方式)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示