在配置 hibernate.cfg.xml 啟用二級緩存時,啟動專案拋出 org.hibernate.MappingException: invalid configuration,根因為 org.xml.sax.SAXParseException:The content of element type "session-factory" must match "(property*,mapping*,(class-cache|collection-cache)*,event*,listener*)"。
Hibernate 的 DTD 強制規定 <session-factory> 內部子元素必須嚴格遵循順序:
<property> — 資料庫連線、方言等屬性配置(最前)<mapping> — 實體映射檔或類別引用<class-cache> / <collection-cache> — 二級緩存策略宣告<event> — 事件監聽器註冊<listener> — 實體生命週期監聽器(最後)常見錯誤是將 <mapping> 置於 <property> 之前,或將緩存配置放在映射之後,導致 XML 驗證失敗。
<session-factory>
<!-- 1. 所有 property 必須在最前 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 2. mapping 緊隨其後 -->
<mapping resource="com/example/User.hbm.xml"/>
<mapping class="com.example.Product"/>
<!-- 3. 緩存策略配置 -->
<class-cache name="com.example.User" usage="read-write"/>
<collection-cache collection="com.example.User.orders" usage="read-only"/>
<!-- 4. 事件與監聽器 -->
<event type="pre-load"><listener class="com.example.MyPreLoadListener"/></event>
<listener class="com.example.MyEntityListener"/>
</session-factory>