zoukankan      html  css  js  c++  java
  • 我的NHibernate

    废话不多说,直接上图:

    这是整个项目的目录结构。

    其中:User.cs代码如下:

    using System;
    using System.Collections;
    
    namespace Modelse
    {
    	#region User
    
    	/// <summary>
    	/// User object for NHibernate mapped table 'user'.
    	/// </summary>
    	public class User
    	{
    		#region Member Variables
    		
    		protected int id;
    		protected string uname;
    
    		#endregion
    
    		#region Constructors
    
    		public User() { }
    
    		public User( string uname )
    		{
    			this.uname = uname;
    		}
    
    		#endregion
    
    		#region Public Properties
    
    		public int Id
    		{
    			get {return id;}
    			set {id = value;}
    		}
    
    		public string Uname
    		{
    			get { return uname; }
    			set
    			{
    				if ( value != null && value.Length > 11)
    					throw new ArgumentOutOfRangeException("Invalid value for Uname", value, value.ToString());
    				uname = value;
    			}
    		}
    
    		
    
    		#endregion
    	}
    	#endregion
    }
    

     User.xml的代码如下:

    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Models" namespace="Models">
    	<class name="User" entity-name="User">
    		<id name="Id" type="Int32" unsaved-value="0">
    			<column name="id" sql-type="int" not-null="true" unique="true" index="PRIMARY"/>
    			<generator class="native" />
    		</id>
    		<property name="Uname" type="String">
    			<column name="uname" length="11" sql-type="varchar" not-null="true"/>
    		</property>
    	</class>
    </hibernate-mapping>
    

     hibernate.cfg.xml的代码如下:

    <?xml version="1.0" encoding="utf-8"?>
    <!-- 
    This template was written to work with NHibernate.Test.
    Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it 
    for your own use before compile tests in VisualStudio.
    -->
    <!-- This is the ByteFX.Data.dll provider for MySql -->
    <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
      <session-factory name="NHibernate.Test">
        <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
        <property name="connection.connection_string">
          server=localhost;database=mytxt;uid=root;pwd=root;
        </property>
        <property name="dialect">NHibernate.Dialect.MySQLDialect</property>
        <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
        <mapping assembly="Models"/>
      </session-factory>
    </hibernate-configuration>
    

     NHibernateHelper.cs的代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using NHibernate.Cfg;
    using NHibernate;
    
    namespace DAL
    {
        public class NHibernateHelper
        {
            private ISessionFactory _sessionFactory;
            public NHibernateHelper()
            {
                _sessionFactory = GetSessionFactory();
            }
            private ISessionFactory GetSessionFactory()
            {
                return (new Configuration()).Configure("hibernate.cfg.xml").BuildSessionFactory();
            }
            public ISession GetSession()
            {
                return _sessionFactory.OpenSession();
            }
    
        }
    }
    

     Helper.cs的代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using NHibernate;
    using NHibernate.Cfg;
    using NHibernate.Cfg.Loquacious;
    using NHibernate.Dialect;
    using NHibernate.Connection;
    using NHibernate.Driver;
    using System.Data;
    using NHibernate.AdoNet;
    using NHibernate.Transaction;
    using NHibernate.Exceptions;
    using NHibernate.Cache;
    using NHibernate.Cfg.MappingSchema;
    using ConfOrm;
    using Modelse;
    using NHibernate.Tool.hbm2ddl;
    using ConfOrm.NH;
    
    namespace DAL
    {
        public class Helper
        {
            private Configuration buildConf() 
            {
                var cfg = new Configuration();
                //Code Snippets Copyright http://lyj.cnblogs.com/
                cfg.SessionFactory()
                   .Integrate
                        .Using<MySQLDialect>()
                        .DisableKeywordsAutoImport()
                        .AutoQuoteKeywords()
                        .LogSqlInConsole()
                        .DisableLogFormatedSql()
                        .Connected
                            .Through<DriverConnectionProvider>()
                            .By<MySqlDataDriver>()
                            .With(IsolationLevel.ReadCommitted)
                            .Releasing(ConnectionReleaseMode.AfterTransaction)
                            .Using("server=localhost;database=mytxt;uid=root;pwd=root;")
                        .BatchingQueries
                            .Through<NonBatchingBatcherFactory>()
                            .Each(15)
                        .Transactions
                             .Through<AdoNetTransactionFactory>()
                         .CreateCommands
                            .Preparing()
                            .WithTimeout(10)
                            .ConvertingExceptionsThrough<SQLStateConverter>()
                            .AutoCommentingSql()
                            .WithMaximumDepthOfOuterJoinFetching(11)
                            .WithHqlToSqlSubstitutions("true 1, false 0, yes 'Y', no 'N'")
                        .Schema
                            .Validating();
    
                //Code Snippets Copyright http://lyj.cnblogs.com/
                cfg.SessionFactory()
                    .Caching
                        .Through<HashtableCacheProvider>()
                        .PrefixingRegionsWith("xyz")
                        .UsingMinimalPuts()
                        .Queries
                            .Through<StandardQueryCache>()
                        .WithDefaultExpiration(15);
                cfg.SessionFactory()
                    .Proxy
                        .DisableValidation()
                        .Through<NHibernate.ByteCode.LinFu.ProxyFactoryFactory>();
                return cfg;
            }
    
            public HbmMapping getMapping() 
            {
                var orm = new ObjectRelationalMapper();
                orm.TablePerClass<User>();
                var mapper = new Mapper(orm);
                return mapper.CompileMappingFor(new[] { typeof(User) });
            }
    
            public Configuration getConf() 
            {
                //配置NHibernate
                var conf = this.buildConf();
                //在Configuration中添加HbmMapping
                conf.AddDeserializedMapping(getMapping(), "User");
                //配置元数据
                SchemaMetadataUpdater.QuoteTableAndColumns(conf);
                //创建数据库架构   这里有问题
                //new SchemaExport(conf).Create(false,true);
                return conf;
            }
    
            public ISessionFactory getFactory() 
            {
                return getConf().BuildSessionFactory();
            }
    
            public ISession getSession() 
            {
                return getFactory().OpenSession();
            }
    
            public void sessionClose(ISession session) 
            {
                session.Close();
            }
        }
    }
    

     Program.cs的代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using DAL;
    using NHibernate;
    using Modelse;
    using NHibernate.Tool.hbm2ddl;
    
    namespace TestNH
    {
        class Program
        {
            static void Main(string[] args)
            {
                Helper helper = new Helper();
                ISession s = helper.getSession();
                User user = new User();
                //user.Id = 2;
                user.Uname = "222";
                int num = (int)s.Save(user);
                s.Flush();
                s.Close();
            }
    
            public void sel() 
            {
                Helper helper = new Helper();
                ISession s = helper.getSession();
                User user = new User();
                Type type = user.GetType();
                user = (User)s.Get(type, 1);
                s.Close();
                string str = user.Uname;   
            }
    
            public void add() 
            {
                Helper helper = new Helper();
                ISession s = helper.getSession();
                User user = new User();
                user.Id = 2;
                user.Uname = "222";
                s.Save(user);
            }
        }
    }
    

     另附:引用图

    这里需要注意的是:User.xml需要在它的属性里面设置为生成操作:嵌入的资源。然后nhibernate下载下来之后在Required_Bins文件夹下有nhibernate-configuration.xsd和nhibernate-mapping.xsd两个文件,需要将他们复制到X:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas目录下,这样可以在VS中添加hibernate配置文件的提示功能。

  • 相关阅读:
    DOM操作CSS
    DOM操作html
    Zendstudio 9.0.2 安装Aptana3 并且配置 jQuery
    Bootstrap
    Emmet:HTML/CSS代码快速编写神器
    用Chrome浏览器模拟手机,android,iphone,ipad访问网站
    jQuery中json对象的复制(数组及对象) .
    json数据处理技巧(字段带空格、增加字段)
    jQuery提升性能技巧及个人总结 .
    不错的jQuery图表插件 .
  • 原文地址:https://www.cnblogs.com/wpcnblog/p/2523748.html
Copyright © 2011-2022 走看看