nhibernate的简单配置与使用

nhibernate的简单配置与使用配置nhibernate的方式有两种,一种是通过xml文件的方式配置,还有就是通过class的方式配置。网上大多数是以xml的方式配置nhibernate,本文则已class的方式来配置,并通过IOC(依赖注入,本文以构造注入)的方式注册nhibernate。下面就以一个demo来说明配置、注入以及使用的方法。创建一个工程,在工程下添加三个项目。1、Web工程(demo采用的是MVC框架)…

大家好,又见面了,我是你们的朋友全栈君。

配置nhibernate的方式有两种,一种是通过xml文件的方式配置,还有就是通过class的方式配置。网上大多数是以xml的方式配置nhibernate,本文则已class的方式来配置,并通过IOC(依赖注入,本文以构造注入)的方式注册nhibernate。下面就以一个demo来说明配置、注入以及使用的方法。

创建一个工程,在工程下添加三个项目。
1、Web工程(demo采用的是MVC框架),在项目下添加一个IOC文件夹,并在文件夹下添加一下类,工程图如图所示:

这里写图片描述

2、web.Model

这里写图片描述

3、web.Service

这里写图片描述

IOC
a. NHibernateModule.cs —-用于nhibernate的注册

namespace Web.Ioc.Module
{
    public class NHibernateModule :Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            /* one application have only one ISessionFactory */
            builder.Register(c => new SessionFactoryProvider())
                   .As<ISessionFactoryProvider>()
                   .SingleInstance();

            /* should be instance per http request to ensure one session per request model */
            builder.Register(c => new SessionProvider(c.Resolve<ISessionFactoryProvider>()))
                   .As<ISessionProvider>()
                   .InstancePerRequest();

            /* should be instance per http request to ensure one session per request model */
            builder.Register(c => new UnitOfWork(c.Resolve<ISessionProvider>()))
                   .As<IUnitOfWork>()
                /* must be, to commit transaction, to close session, or will lost data and occupied db connection */
                //.OnRelease(uow => uow.Close()) // 如果有继承IDispose接口 则可以不用显示调用
                   .InstancePerRequest();
        }
    }
}

b. ServiceModule.cs —–用于service的注册

namespace Web.Ioc.Module
{
    public class ServiceModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterGeneric(typeof(Service<>))
                .As(typeof(IService<>))
                .InstancePerRequest();
        }
    }
}

c. IocConfig.cs 用于注册nhibernate和service

namespace Web.Ioc
{
    public class IocConfig
    {
        public static void Register(/*params Assembly[] contorllerAssemblies*/)
        {
            var builder = new ContainerBuilder();

            builder.RegisterModule(new NHibernateModule());//注册nhibernate
            builder.RegisterModule(new ServiceModule());//注册service

            // register controller.
            //注册Controller。因为框架是采用构造注入的方式
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // register api controller
            builder.RegisterApiControllers(typeof(MvcApplication).Assembly);

            // register filters
            // global filters is not working
            builder.RegisterFilterProvider();

            var container = builder.Build();
            // Configure contollers with the dependency resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Configure Web API with the dependency resolver
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
    }
}

在Global.asax的Application_Start调用Register。如图:
这里写图片描述

Web.Model:该项目先主要存放数据实体以及实体对应数据库的映射。即nhibernate的mapping。

demo中的实体类:

namespace Web.Model
{
    public class Barcode : EntityBase
    {
        public Barcode()
        {
            Active = 0;
        }

        public virtual string ItemNumber { get; set; }

        public virtual long LastSerialNbr { get; set; }

        public virtual long MinSerialNbr { get; set; }

        public virtual long MaxSerialNbr { get; set; }

        public virtual int Active { get; set; }

        public virtual int CreatedId { get; set; }

        public virtual DateTime CreatedTime { get; set; }

        public virtual int ModifiedId { get; set; }

        public virtual DateTime ModifiedTime { get; set; }
    }
}

demo中的mapping类:

namespace Web.Model.Mapping
{
    public class BarcodeMapping : EntityBaseMapping<Barcode>
    {
        public BarcodeMapping()
            : base("wp_barcode")
        {
            Property(b => b.ItemNumber, m => m.Column("item_number"));
            Property(b => b.LastSerialNbr, m => m.Column("last_serial_nbr"));
            Property(b => b.MinSerialNbr, m => m.Column("min_serial_nbr"));
            Property(b => b.MaxSerialNbr, m => m.Column("max_serial_nbr"));
            Property(b => b.Active, m => m.Column("active"));
            Property(b => b.CreatedId, m => m.Column("created_id"));
            Property(b => b.CreatedTime, m => m.Column("created_time"));
            Property(b => b.ModifiedId, m => m.Column("modified_id"));
            Property(b => b.ModifiedTime, m => m.Column("modified_time"));
        }
    }
}

Web.Service:—-该模块主要包含用与nhibernate的ISession注册的类,以及数据库的交互。主要类:

SessionProvider :获取nhibernate的session

namespace Web.Service
{
    /// <summary>
    /// wrapping ISesion so that other assembly needn't to reference NHibernate.dll 
    /// </summary>
    public class SessionProvider : ISessionProvider
    {
        private readonly Lazy<ISession> session;

        public ISession Session
        {
            get { return session.Value; }
        }

        public SessionProvider(ISessionFactoryProvider sessionFactoryProvider)
        {
            session = new Lazy<ISession>(() => sessionFactoryProvider.SessionFactory.OpenSession());
        }
    }
}

SessionFactoryProvider :注册数据库连接以及mapping

using System.Data;
using System.Reflection;
using System.Linq;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using Web.Model.Mapping;


namespace Web.Service
{
    /// <summary>
    /// wrapping ISesionFactory so that other assembly needn't to reference NHibernate.dll 
    /// </summary>
    public class SessionFactoryProvider : ISessionFactoryProvider
    {
        private static readonly ISessionFactory sessionFactory;

        private static Configuration Configuration { get; set; }

        #region ISessionFactoryProvider 成员

        public ISessionFactory SessionFactory
        {
            get { return sessionFactory; }
        }

        #endregion

        static SessionFactoryProvider()
        {

            Configuration = BuildConfiguration();
            sessionFactory = Configuration.BuildSessionFactory();

        }

        //注册pgsql
        private static Configuration BuildConfiguration()
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionStringName = "pgsqlConn";//对应config中的数据库连接字符串
                    db.Dialect<PostgreSQL82Dialect>();
                    db.Driver<NpgsqlDriver>();
                    db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                    db.IsolationLevel = IsolationLevel.ReadCommitted;
                    db.BatchSize = 100;
                    db.LogFormattedSql = true;
                    db.AutoCommentSql = true;
#if DEBUG
                    db.LogSqlInConsole = true;
#endif
                });

            cfg.AddMapping(BuildMappings());
            /* Not supported in PostgreSQL */
            //SchemaMetadataUpdater.QuoteTableAndColumns(cfg);

            return cfg;
        }

        /// <summary>
        /// 通过Mapping映射的方式注册Nhibernate
        /// </summary>
        /// <returns></returns>
        private static HbmMapping BuildMappings()
        {
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly
                                   .GetAssembly(typeof(TestMapping))//获取TestMapping所在的程序集,即Web.Model
                                   .GetExportedTypes()
                                   .Where(t => t.Name.EndsWith("Mapping")));
            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            return mapping;
        }


        //通过xml的方式注册nhibernate
// public static string BuildMappingsXml()
// { 
   
// var mapper = new ModelMapper();
// mapper.AddMappings(Assembly
// .GetAssembly(typeof(UserMapping))
// .GetExportedTypes()
// .Where(t => t.Name.EndsWith("Mapping")));
// var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
// return mapping.AsString();
// }

    }
}

最后调用的方式就特别简单了,在controller中(demo为homeController)


        private readonly IService<Barcode> testService;//声明对象

        //以构造函数的方式注入
        public HomeController(IService<Barcode> testService)
        {
            this.testService = testService;
        }

        public ActionResult Index()
        {
            List<Barcode> list = testService.Queryable(o => o.Active == 0).ToList();//调用service
            return View();
        }

在web.config中添加连接字符串:

 <connectionStrings> <add name="pgsqlConn" connectionString="Server=xxx.xxx.xx.xx;Port=****;User Id=****;Password=****;Database=****;" / </connectionStrings>

demo源代码:
源代码

ps:项目采用NuGet管理dll,为防止上传文件过大,所有未上传packages文件夹。下好代码后,直接重新生成,即可自动还原NuGet包。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/159185.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 基于STM32F4单片机对步进电机的控制(有代码)

    基于STM32F4单片机对步进电机的控制(有代码)步进电机是将电脉冲控制信号转变为角位移或线位移的一种常用的数字控制执行元件,又称为脉冲电机。在驱动电源的作用下,步进电机受到脉冲的控制,其转子的角位移量和速度严格地与输入脉冲的数量和脉冲频率成正比。步进电机每接收一个电脉冲,转子就转过一个相应的角度(步距角)。改变通电顺序可改变步进电动机的旋转方向;改变通电频率可改变步进电动机的转速。因此,通过控制输入电脉冲的数目、频率及电动机绕组的通电顺序就可以…

    2022年5月6日
    490
  • AIC准则选三个变量的r语言代码

    AIC准则选三个变量的r语言代码setwd(“C:/Users/IBM/Desktop/研一课程/2.2回归分析/回归作业”) #设定当前的工作目录shuju=read.table(“shuju.txt”,header=T)shuju #读取数据#采用AIC原则自动选择模型-前进法library(MASS)stepAIC(lm(y~.,data=shuju[,-1])) #146.

    2022年5月24日
    86
  • FindWindowEX应用实例二则[通俗易懂]

    FindWindowEX应用实例二则[通俗易懂]函数功能:该函数获得一个窗口的句柄,该窗口的类名和窗口名与给定的字符串相匹配。这个函数查找子窗口,从排在给定的子窗口后面的下一个子窗口开始。在查找时不区分大小写。    函数原型:HWNDFindWindowEx(HWNDhwndParent,HWNDhwndChildAfter,LPCTSTRlpszClass,LPCTSTRlpszWindow);    参数;    hwndPar

    2022年5月6日
    37
  • iOS开发之duplicate symbols for architecture x86_64错误

    iOS开发之duplicate symbols for architecture x86_64错误

    2021年5月27日
    107
  • OpenNebula 4.0 Beta 新特性介绍

    OpenNebula 4.0 Beta 新特性介绍

    2021年8月31日
    55
  • windows10上安装mysql(详细步骤)

    windows10上安装mysql(详细步骤)windows安装mysql(详细步骤)环境:windwos10(1511)、mysql5.7.14时间:2016年9月5日一、下载mysql1.在浏览器里打开mysql的官网http://www.mysql.com/2.进入页面顶部的”Downloads”3.打开页面底部的“Community(GPL)Downloads”

    2022年5月6日
    129

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号