1. 程式人生 > 實用技巧 >NHibernate.HibernateException:“Unable to locate persister for the entity named 'Domain.Entity.LeaseUser'. - The mapping for 'Domain.Entity.LeaseUser' was not added to the NHibernate co

NHibernate.HibernateException:“Unable to locate persister for the entity named 'Domain.Entity.LeaseUser'. - The mapping for 'Domain.Entity.LeaseUser' was not added to the NHibernate co

在使用NHiberanter,建立一個session上下文,進行語句執行時,出現了標題所示錯誤。控制檯呼叫程式碼如下:

 public  static void Main(string[] args)
        {
            //NHibernateProfiler程式分析初始化
            //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
            ISessionFactory factory = new Configuration().Configure().BuildSessionFactory();
             ISession session 
= factory.OpenSession(); using (ITransaction rs = session.BeginTransaction()) { var pm = session.Get<LeaseUser>(154143);//出現錯誤 var _model = session.QueryOver<LeaseUser>().Where(x => x.UserName=="陶*林").List(); var sModel = session.CreateSQLQuery("
select * from LEASE_USER where user_name=:num").AddEntity(typeof(LeaseUser)) .SetParameter("num", "包磊");

通過session的get方法,獲取一個指定實體,提示持久化物件沒有在配置檔案中載入到。配置檔案如下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!-- 
 3 This template was written to work with NHibernate.Test.
 4 Copy the template to your NHibernate.Test project folder and rename it in
hibernate.cfg.xml and change it 5 for your own use before compile tests in VisualStudio. 6 --> 7 <!-- This is the System.Data.OracleClient.dll provider for Oracle from MS --> 8 <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> 9 <session-factory name="NHibernate.Test"> 10 <property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property> 11 <property name="connection.connection_string"> 12 User ID=admin;Password=admin001;Data Source=127.0.0.1/orcl 13 </property> 14 <property name="show_sql">true</property> 15 <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property> 16 <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property> 18 </session-factory> 19 </hibernate-configuration>

誘因一:該配置時直接從下載的Nh包中的oracle.cfg.xml移植過來的,通過查詢資料,發現少了一行:<mapping assembly="Domain"/>,該mapping需要新增在session-factory的最後位置,其目的是載入持久化物件的對映檔案的所在程式集:

1 <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>
2         <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
3         <mapping assembly="Domain"/><!--用於載入實體對映檔案所在的程式集-->
4     </session-factory>

誘因二:與Fluent Nhibernate混餚了。使用如下程式碼片段載入hibernate配置檔案,它會去查詢配置檔案mapping配置的程式集下的所有xml對映檔案,因為使用了Fluent Nhibernate的map對映,所以是查找不出對應的xml,也即持久化物件的對映未在配置中查詢到:

1 ISessionFactory factory = new Configuration().Configure().BuildSessionFactory();

備忘:

  一。向專案中新增指定的資料庫xx.cfg.xml檔案的時候,需要統一修改名稱為:hibernate.cfg.xml

  二。hibernate.cfg.xml檔案屬性->複製到輸入目錄->始終複製或如果較新則複製

  三。直接引入的資料庫對應的cfg.xml檔案,是沒有mapping節點的。但這個是必不可少的屬性節點。