- Configuration cfg = new Configuration().addResource("com/demo/hibernate/beans/User.hbm.xml");
2 爲Configuration指定持久化類
一個替代的方法是指定被映射的類 讓Hibernate幫你尋找映射定義文件
- Configuration cfg = new Configuration().addClass(com.demo.hibernate.beans.User.class);
Hibernate將會在類路徑中需找名字爲 /com/demo/hibernate/beans/User.hbm.xml 映射定義文件 消除了任何對文件名的硬編譯
3 爲Configuration指定配置屬性
Configuration也允許指定配置屬性
-
Configuration cfg =new Configuration().addClass(com.demo.hibernate.beans.User.class)
-
.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLInnoDBDialect")
-
.setProperty("hibernate.connection.datasource","java:comp/env/jdbc/test")
- .setProperty("hibernate.order_update","true");
4 Configuration的三種加載方式
在Hibernate的啓動與開發流程中 要使用一個Configuration 需要爲他設置三個方面的內容
數據庫連接屬性
hbm.xml文件
POJO類
其中 第二個和第三個只需要設置一個 就會自動需找另一個 因爲這兩者只需一個
第一種方式是使用hibernate.cfg.xml 該文件設置了數據庫連接的屬性和hbm.xml映射文件配置 hibernate會自動加載該配置屬性 並自動找到POJO 因此要取得Configuration對象 只需要簡單的創建改對象即可
- Configuration cfg = new Configuration();
- cfg.configuration("hibernate.cfg.xml");
第二種方式是通過hibernate.properties 省略
第三種方式是完全在構造時進行硬編碼設置 設置過程如下所示
- Configuration cfg =new Configuration()
-
.addClass(com.demo.hibernate.beans.User.class)
-
.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLInnoDBDialect")
-
.setProperty("hibernate.connection.datasource","java:comp/env/jdbc/test")
- .setProperty("hibernate.order_update","true");
第一種方式是我們最常用的方式