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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • dataframe分割数据_语篇语义框架研究

    dataframe分割数据_语篇语义框架研究mmSegmentation开源语义分割框架详细入门教程,含自定义数据集、模型选择、训练参数设定等

    2022年8月21日
    10
  • 启动ucosii之四OSTaskCreate()[通俗易懂]

    启动ucosii之四OSTaskCreate()[通俗易懂]函数原型来自OS_TASK.C/***********************************************************************************************************                                           CREATEATASK**************

    2025年9月21日
    6
  • 图的同构[通俗易懂]

    图的同构[通俗易懂]图的同构Abstract图的同构为什么要研究图的同构满足什么条件的图才是图的同构同构的图案例任意两个图形,如何判定图的同构图同构的必要条件,也就是说两个图如果同构,会存在的特征图同构的必要条件举例Abstract声明:本文只为我闲暇时候学习所做笔记,仅供我无聊时复习所用,若文中有错,误导了读者,敬请谅解!!!图的同构参见我的语雀:图论:https://www.yuque.com/jhongt…

    2022年4月19日
    84
  • 三极管的饱和导通条件[通俗易懂]

    三极管的饱和导通条件[通俗易懂]请看图,假设三极管基极电流为1MA,三极管直流放大倍数为50,那么在三极管集电极就有50MA电流。这时如果RL取100Ω,那么在RL两端分得电压5V,而另5V就加在三极管上,这时三极管处于正常放大状态。如果RL取300Ω呢?根据计算。在RL上应该分得15V电压。如果电源电压超过15V,那么这个电路仍处于放大壮态。可这里电源电压只有10V,那么这10V电压几乎全加在了电阻上,而三极管…

    2022年6月29日
    93
  • 深信服SCSA安全工程师题库(方便大家复习备考)

    深信服SCSA安全工程师题库(方便大家复习备考)1、【EDR】下列哪个端口是紧急情况下EDR管理平台和客户端通信端口,即紧急情况下用于下发Agent重启、Agent卸载和Agent停止等指令。()A:443.0B:54120.0C:8083.0D:8088.0正确答案B2、【EDR】客户有7000个终端需要安装EDR客户端进行安全防护,请问推荐部署多少个EDR管理平台()A:1个B:2个C:4个D:6个正确答案C3、【EDR】EDR的Agent客户端不支持在以下哪种类型的终端上安装()A:WindowsServerB

    2022年6月20日
    50
  • 双线性插值(Bilinear Interpolation)[通俗易懂]

    双线性插值(Bilinear Interpolation)[通俗易懂]双线性插值(BilinearInterpolation)  假设源图像大小为mxn,目标图像为axb。那么两幅图像的边长比分别为:m/a和n/b。注意,通常这个比例不是整数,编程存储的时候要用浮点型。目标图像的第(i,j)个像素点(i行j列)可以通过边长比对应回源图像。其对应坐标为(i*m/a,j*n/b)。显然,这个对应坐标一般来说不是整数,而非整数的坐标是无法在图像这种离散数据上使用…

    2022年6月10日
    58

发表回复

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

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