Spring.Net集成NHibernate配置

原创 2015年07月06日 17:45:36

NHibernate是一个面向.NET环境的对象/关系数据库映射工具(ORM)。用来把对象模型表示的对象映射到基于SQL的关系模型数据结构中去。NHibernate可以单独使用,Spring.Net集成NHibernate之后可以减少不少配置,其中包括数据库配置文件的映射。

配置如下:

  • 配置文件

    OrmService.xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
         xmlns:db="http://www.springframework.net/database" 
         default-autowire="byName">

  <!-- 数据库和Nhibernate的相关配置 -->
  <db:provider id="DbProvider"
                   provider="System.Data.SqlClient"
                   connectionString="Data Source=${db.datasource};Database=${db.database};User Id=${db.user};Password=${db.password};"/>

  <object id="NHibernateSessionFactory" type="SessionFactory.LocalSessionFactoryObject,SessionFactory">
    <property name="DbProvider" ref="DbProvider"/>
    <property name="EntityAssemblyNames">
      <list>
        <value>Entity</value>
      </list>
    </property>
    <!--<property name="MappingAssemblies">
      <list>
        <value>Entity</value>
      </list>
    </property>-->
    <property name="HibernateProperties">
      <dictionary>
        <entry key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
        <entry key="dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
        <entry key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
        <entry key="show_sql" value="false" />
        <entry key="adonet.batch_size" value="50"/>
        <entry key="command_timeout" value="300"/>
        <entry key="query.substitutions" value="true 1, false 0, yes 'Y', no 'N"/>

        <!--Nhibernate-->
        <entry key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
        <entry key="hibernate.show_sql" value="false" />
        <entry key="hibernate.format_sql" value="false"/>

        <!--<entry key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />-->
        <!--二级缓存-->
        <entry key="cache.provider_class" value="NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache" />
        <!--<entry key="cache.provider_class" value="NHibernate.Cache.HashtableCacheProvider,NHibernate" />-->
        <entry key="cache.use_second_level_cache" value="false" />
        <entry key="cache.use_query_cache" value="false" />
        <entry key="cache.default_expiration" value="3000" />
        <entry key="cache.region_prefix" value="8seasons" />
      </dictionary>
    </property>
    <property name="ExposeTransactionAwareSessionFactory" value="true" />
  </object>

  <object id="HibernateTemplate" type="Spring.Data.NHibernate.Generic.HibernateTemplate">
    <property name="SessionFactory" ref="NHibernateSessionFactory" />
    <property name="TemplateFlushMode" value="Auto" />
    <property name="CacheQueries" value="true" />
  </object>

  <object id="transactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate32">
    <property name="DbProvider" ref="DbProvider" />
    <property name="SessionFactory" ref="NHibernateSessionFactory"/>
  </object>

  <object  type="Spring.Aop.Framework.AutoProxy.ObjectNameAutoProxyCreator,Spring.Aop">
    <property name="ObjectNames">
      <list>
        <value>*Service</value>
      </list>
    </property>
    <property name="interceptorNames">
      <list>
        <value>transactionInterceptorName</value>
      </list>
    </property>
  </object>
  <!--拦截器,定义事务策略-->
  <object id="transactionInterceptorName" type="Spring.Transaction.Interceptor.TransactionInterceptor,Spring.Data">
    <property name="transactionAttributes">
      <name-values>
        <add key="Get*" value="PROPAGATION_REQUIRED,readOnly"/>
        <add key="Find*" value="PROPAGATION_REQUIRED,readOnly"/>
        <add key="AdminFind*" value="PROPAGATION_REQUIRED,readOnly"/>
        <add key="Load*" value="PROPAGATION_REQUIRED,readOnly"/>
        <add key="Search*" value="PROPAGATION_REQUIRED,readOnly"/>
        <add key="Is*" value="PROPAGATION_REQUIRED,readOnly"/>
        <add key="SendCoupon*" value="PROPAGATION_REQUIRES_NEW"/>
        <add key="*" value="PROPAGATION_REQUIRED"/>
      </name-values>
    </property>
    <property name="transactionManager">
      <ref local="transactionManager" />
    </property>
  </object>
</objects>

config.xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.net   
        http://www.springframework.net/xsd/spring-objects.xsd" default-autowire="byName">

  <object type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core">
    <property name="Locations">
      <list>
        <value>file://~/config/deploy.xml</value>
      </list>
    </property>
    <property name="ConfigSections" value="spring-config"/>
  </object>

</objects>

deploy.xml

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <spring-config>
    <!--Begin 数据库配置-->
    <add key="db.datasource" value="127.0.0.1"/>
    <add key="db.database" value="NHTest"/>
    <add key="db.user" value="sa"/>
    <add key="db.password" value="sa"/>
  </spring-config>
</configuration>

IocService.xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.net   
        http://www.springframework.net/xsd/spring-objects.xsd" default-autowire="byName">

  <object id="Student" type="Entity.Student,Entity"></object>
  <object id="Persona" type="Entity.Persona,Entity"></object>

  <object id="StudentService" type="ServiceImpl.Student.StudentService,ServiceImpl"></object>
  <object id="StudentDao" type="ServiceImpl.Student.Dao.StudentDao,ServiceImpl"></object>

  <!--3.该对象需要放在最后-->
  <object id="ServiceFactory" type="Service.ServiceFactory,Service" singleton="true"/>
</objects>

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc4" />
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
      <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core" />
    </sectionGroup>
  </configSections>

  <spring>
    <context>
      <resource uri="config://spring/objects" />
      <resource uri="assembly://MvcApplication1/MvcApplication1.config/config.xml"></resource>
      <resource uri="assembly://MvcApplication1/MvcApplication1.config/IocService.xml"></resource>
      <resource uri="assembly://MvcApplication1/MvcApplication1.config/OrmService.xml"></resource>
    </context>
    <objects xmlns="http://www.springframework.net" />
  </spring>

</configuration>
  • 创建Po实体 (可以使用动软直接生成)
using NHibernate.Mapping.Attributes;//此处需要引用Spring.Data.NHibernate32.dll
namespace Entity
{
    //"Student"为数据库表名
    [Class(Table = "Student", Lazy = false, NameType = typeof(StudentPo), DynamicUpdate = true)]
    [Cache(Usage = CacheUsage.NonStrictReadWrite)]
    public class StudentPo
    {
        [Id(1, Name = "Id", Column = "Id")]//主键和对应的表列名
        [Generator(2, Class = "native")]//自增
        public virtual int Id        {            get;            set;        }

        [Property(Column = "Number")]//对应的表列名
        public virtual string Number        {            get;            set;        }

        [Property(Column = "Name")]
        public virtual string Name        {            get;            set;        }

        [Property(Column = "Address")]
        public virtual string Address        {            get;            set;        }

        [Property(Column = "Phone")]
        public virtual string Phone        {            get;            set;        }

        [Property(Column = "`Sex`")]
        //数据库字段可为空,属性值也必须可为空,如果列名为关键字需要用``符号包起来,此处Sex只是一个例子并非关键字。
        public virtual int? Sex        {            get;            set;        }

        [Property(Column = "IsChinese")]
        public virtual bool? IsChinese        {            get;            set;        }                  
    }
}
  • LocalSessionFactoryObject
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Mapping.Attributes;

namespace SessionFactory
{
    public class LocalSessionFactoryObject : Spring.Data.NHibernate.LocalSessionFactoryObject
    {
        public string[] EntityAssemblyNames { get; set; }

        protected override void PostProcessConfiguration(NHibernate.Cfg.Configuration config)
        {
            Initialize(config);
            base.PostProcessConfiguration(config);
        }

        protected void Initialize(NHibernate.Cfg.Configuration config)
        {
            using (var stream = new MemoryStream())
            {
                HbmSerializer.Default.Validate = true;

                foreach (var modelAssemblyName in EntityAssemblyNames)
                {
//生成NHibernate配置保存到内存中,个人理解:手动生成的NHibernate配置文件最终也是读到内存中
//HbmSerializer.Default.Serialize(@"D:\test\",Assembly.Load(modelAssemblyName));

                    HbmSerializer.Default.Serialize(stream, Assembly.Load(modelAssemblyName));

                    stream.Position = 0;

                    config.AddInputStream(stream);
                }
            }
        }
    }
}
  • IBaseDao和BaseDao 封装了对PO对象【持久对象(Persisent Object)】的增,删,改,查,分页等操作。
    public interface IBaseDao<T, PK>
    {
        //...
    }
    public class BaseDao<T, PK> : HibernateDaoSupport, IBaseDao<T, PK>
    {
        //...
    }
  • Service层
    public class StudentVo
    {
        public virtual int Id        {            get;            set;        }
        public virtual string Number        {            get;            set;        }
        public virtual string Name        {            get;            set;        }
        public virtual string Address        {            get;            set;        }
        public virtual string Phone        {            get;            set;        }
        public virtual int? Sex        {            get;            set;        }
        public virtual bool? IsChinese        {            get;            set;        }

    }

    public interface IStudentDao : IBaseDao<StudentPo, int>
    {
    }

    public interface IStudentService
    {
        int SetStudent(StudentVo studentVo);
    }
  • ServiceImpl层
    public class StudentDao : BaseDao<StudentPo, int>, IStudentDao
    {
    }

    public class StudentService : IStudentService
    {
        public IStudentDao StudentDao { private get; set; }

        public int SetStudent(StudentVo studentVo)
        {
            int id;
            if (studentVo.Id == 0)
            {
                id = StudentDao.AddObject(GetStudentPoFromVo(studentVo));
            }
            else
            {
                id = studentVo.Id;
                StudentDao.UpdateObject(GetStudentPoFromVo(studentVo));
            }
            return id;
        }

        internal static StudentVo GetStudentVoFromPo(StudentPo studentPo)
        {
            StudentVo studentVo = null;
            if (!studentPo.IsNullOrEmpty())
            {
                studentVo = new StudentVo
                {
                    Address = studentPo.Address,
                    Id = studentPo.Id,
                    IsChinese = studentPo.IsChinese,
                    Name = studentPo.Name,
                    Number = studentPo.Number,
                    Phone = studentPo.Phone,
                    Sex = studentPo.Sex
                };
            }
            return studentVo;
        }

        internal static StudentPo GetStudentPoFromVo(StudentVo studentVo)
        {
            StudentPo studentPo = null;
            if (!studentVo.IsNullOrEmpty())
            {
                studentPo = new StudentPo
                {
                    Address = studentVo.Address,
                    Id = studentVo.Id,
                    IsChinese = studentVo.IsChinese,
                    Name = studentVo.Name,
                    Number = studentVo.Number,
                    Phone = studentVo.Phone,
                    Sex = studentVo.Sex
                };
            }
            return studentPo;
        }
    }
  • 调用
        public ActionResult Index()
        {
            ServiceFactory.StudentService.SetStudent(new StudentVo
            {
                Address = "China",
                IsChinese = true,
                Name = "wangqi",
                Number = "30801234",
                Phone = "15088888888",
                Sex = 1,
            });
            return View();
        }
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

html 自动跳转到 Ftp 地址

FTP directory /duplo at fan Hello<

【Spring学习】Bean生命周期

我理解的Bean生命周期包括两个方面: Bean何时创建,何时销毁 Bean从创建到销毁的执行流程 一、Bean创建与销毁       Bean的创建时机主要由几个配置项共同来决定,包括: scope...
  • pur_e
  • pur_e
  • 2016-06-21 14:24
  • 5039

Bean在Spring容器中的生命周期

配置在Spring中的Bean在Spring容器中从加载到销毁会经历那些过程呢?如果实现一些特定的Spring接口,这些特定接口的方法会在什么时候被调用呢?本文简单介绍一下这些过程. Bean在Sp...

Spring核心技术(四)——Spring的依赖及其注入(续二)

前面两篇文章描述了IoC容器中依赖的概念,包括依赖注入以及注入细节配置。本文将继续描述玩全部的依赖信息。使用 depends-on如果一个Bean是另一个Bean的依赖的话,通常来说这个Bean也就是...

Spring管理的bean的生命周期1(转)

关键字: lazy-init,init-method,destroy-method,depends-on的说明  lazy-init,init-method,destroy-method,depend...

Spring Bean的生命周期(非常详细)

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring...

Spring核心技术(一)——IoC容器和Bean简介

IoC容器和Bean简介 这章包括了Spring框架对于IoC规则的实现。Ioc也同DI(依赖注入)。而对象是通过构造函数,工厂方法,或者一些Set方法来定义对象之间的依赖的。容器在创建这些Bean对...

Spring核心技术(六)——Spring中Bean的生命周期

前文已经描述了Bean的作用域,本文将描述Bean的一些生命周期作用,配置还有Bean的继承。定制Bean生命周期回调开发者通过实现Spring的InitializeingBean和Disposabl...

Java Persistence with MyBatis 3(中文版) 第四章 使用注解配置SQL映射器

在上一章,我们看到了我们是怎样在映射器Mapper XML配置文件中配置映射语句的。MyBatis也支持使用注解来配置映射语句。当我们使用基于注解的映射器接口时,我们不再需要在XML配置文件中配置了。...

Java内存管理(三)——卡片表

在垃圾回收的过程中,会碰到一个问题,就是老年代中的对象可能引用年轻代中的对象。在这种情况下,每次遍历老年代的对象来查找所有存活对象的时候就会消耗相当的时间。而且,在应用中,通常来说,这种引用是非常少的...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)