Hibernate 可程式化的配置方式

來源:互聯網
上載者:User

org.hibernate.cfg.Configuration 執行個體代表了一個應用程式中 Java 類型到SQL資料庫映射的完整集合。org.hibernate.cfg.Configuration 被用來構建一個(不可變的(immutable))org.hibernate.SessionFactory。映射定義則由不同的
XML 映射定義檔案編譯而來。

你可以直接執行個體化 org.hibernate.cfg.Configuration 來擷取一個執行個體,並為它指定 XML 映射定義檔案。如果映射定義檔案在類路徑(classpath)中,請使用 addResource()。例如:

Configuration cfg = new Configuration()    .addResource("Item.hbm.xml")    .addResource("Bid.hbm.xml");

一個替代方法(有時是更好的選擇)是,指定被映射的類,讓 Hibernate 幫你尋找映射定義檔案:

Configuration cfg = new Configuration()    .addClass(org.hibernate.auction.Item.class)    .addClass(org.hibernate.auction.Bid.class);

Hibernate 將會在類路徑(classpath)中尋找名字為 /org/hibernate/auction/Item.hbm.xml 和/org/hibernate/auction/Bid.hbm.xml 映射定義檔案。這種方式消除了任何對檔案名稱的寫入程式碼(hardcoded)。

org.hibernate.cfg.Configuration > 也允許你指定配置屬性。例如:

Configuration cfg = new Configuration()    .addClass(org.hibernate.auction.Item.class)    .addClass(org.hibernate.auction.Bid.class)    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")    .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")    .setProperty("hibernate.order_updates", "true");

當然這不是唯一的傳遞 Hibernate 配置屬性的方式,其他可選方式還包括:

  1. 傳一個 java.util.Properties 執行個體給 Configuration.setProperties()。

  2. 將 hibernate.properties 放置在類路徑(classpath)的根目錄下(root directory)。

  3. 通過 java -Dproperty=value 來設定系統(System)屬性。

  4. 在 hibernate.cfg.xml 中加入元素 <property>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.