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:

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

  

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
}

  

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; }
    }
}

  

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");
        }
    }
}

  

 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

  

 

    public class StaffManagerRepository : Repository<StaffManager> {

    } /

  Web.config:

  <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>

  

objects.xml
    <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>

  

你可能感兴趣的:(Fluent NHibernate and Spring.net)