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


相关推荐

  • java 异步调用接口_Java接口异步调用[通俗易懂]

    java 异步调用接口_Java接口异步调用[通俗易懂]java接口调用从调用方式上可以分为3类:同步调用,异步调用,回调;同步调用基本不用说了,它是一种阻塞式的调用,就是A方法中直接调用方法B,从上往下依次执行。今天来说说异步调用。什么是异步调用?我的理解就是在方法A中调用方法B,但是方法B很耗时,如果是同步调用的话会等方法B执行完成后才往下执行,如果异步的话就是我调用了方法B,它给我个返回值证明它已接受调用,但是它并没有完成任务,而我就继续往下执行…

    2022年7月11日
    213
  • manjaro 安装分区以及配置方案

    manjaro 安装分区以及配置方案制作启动盘windows下制作启动盘推荐在windows下使用Rufus工具来制作启动盘,做成启动盘后还能用来存储文件linux下制作启动盘使用dd命令,使用该命令做成启动盘后U盘就不能用来存储文件了,具体命令格式可以看wikihttps://wiki.manjaro.org/index.php?title=Burn_an_ISO_File#Using_t…

    2022年6月7日
    70
  • pycharm安装后运行不了_pycharm暂停程序

    pycharm安装后运行不了_pycharm暂停程序原博客链接:http://blog.csdn.net/qingyuanluofeng/article/details/46501427问题:pycharm安装后不能执行python脚本。我的是执行后老是报错,但是之前在cpython中都是可以的。于是上网查询解决方法原因:pycharm没有设置解析器/解释器设置错误(我的就是因为这个之前设置错了,位置也是错的,结果导致程序不能正常运行出

    2022年8月28日
    4
  • 下拉框插件select2的使用

    下拉框插件select2的使用

    2021年11月9日
    50
  • mbus总线是什么意思_Can总线如何配置500k波特率

    mbus总线是什么意思_Can总线如何配置500k波特率MBus总线上自动波特率识别1、通过前导字节0x68,捕获引脚通过1、0比特的两个上升沿的差值除以2来自动识别出波特率。2、为什么是通过两个上升沿,而不是一个上升沿一个下降沿,比如两个比特11的长度除以2来计算?因为两条平行的MBUS总线间存在电容效应,在实验室里面由于线比较短,不容易测试出来,但在实际产品使用中是真实存在的,因此在实验室里面分别用10nf、47nf、23n…

    2022年10月8日
    2
  • 使用adb命令安装apk到手机

    使用adb命令安装apk到手机第一步让真机与电脑相连,cmd打开dos命令窗口(打开cmd的快捷键是Windows+R).第二步输入adbdevices查看手机与电脑是否连接成功,能看到设备信息就代表设备已经连接成功了.第三步紧接着就可以安装apk了.首次要知道自己的apk放在哪个盘符的文件里了.比如我的apk放在E:\data里.进入apk文件所在的目录:输入…

    2022年6月7日
    749

发表回复

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

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