关闭

Spring.Net集成NHibernate配置

标签: 配置nhibernatespring-net
306人阅读 评论(0) 收藏 举报
分类:

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();
        }
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9081次
    • 积分:310
    • 等级:
    • 排名:千里之外
    • 原创:21篇
    • 转载:3篇
    • 译文:1篇
    • 评论:1条
    最新评论