初次玩NHibernate,就遇到一個攔路虎,報錯如下:Could not compile the mapping document: NhibernateForm.NhibernateForm.Student.hbm.xml
不可否認是*.hbm.xml這個文件配置有誤,但是查找了半天都沒找到原因。
最后在http://blog.csdn.net/tyh800220/article/details/1733133 找到解決方案,感謝博主。
解決方案:
<class name="NhibernateForm.Student,NhibernateForm" discriminator-value="0" >
重點在name這個屬性,加上程序集即可。
但是查閱官方的API文檔,也是如此:
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="QuickStart" assembly="QuickStart"> <class name="Cat" table="Cat"> <!-- A 32 hex character is our surrogate key. It's automatically generated by NHibernate with the UUID pattern. --> <id name="Id"> <column name="CatId" sql-type="char(32)" not-null="true"/> <generator class="uuid.hex" /> </id> <!-- A cat has to have a name, but it shouldn' be too long. --> <property name="Name"> <column name="Name" length="16" not-null="true" /> </property> <property name="Sex" /> <property name="Weight" /> </class> </hibernate-mapping>
然而,然而,讓我感覺奇怪的是,官方給出的Demo中卻又把程序集加上了。如下:
<?xml version="1.0" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
<class
name="NHibernate.DomainModel.A, NHibernate.DomainModel"
discriminator-value="0"
>
<id
name="Id" column="identifier_column"
unsaved-value="0"
>
<generator class="increment" />
<!-- unsaved-value used to be null and generator was increment in h2.0.3 -->
</id>
...
這讓我嚴重懷疑官方的API中的示例是否經過了測試。
我用的NHibernate版本是3.3.1,感覺NH各個版本的配置有蠻多差別,而這些細微的差別會導致很多問題,這讓那些后來學習者增添了很多煩惱。感覺學習的主動性要把握在自己的手里僅有兩條路可走:1、閱讀官方E文文檔;2、閱讀源碼。這也是最好的兩種學習方法。
修正:
經過再次仔細閱讀官方API文檔說明,看到如下這句話,讓我頓悟:
If you are not using assembly and namespace attributes, you have to specify fully-qualified class names, including
the name of the assembly that classes are declared in.
也就是說:
如果Map映射文件中的hibernate-mapping節點屬性中沒有設置assembly 和namespace ,那么class節點中就必須使用限定名,類名和程序集都必須定義。而我就是在hibernate-mapping節點沒有設置assembly 和namespace ,class節點也沒有使用全名稱的情況下出的錯誤。