hibernate設定檔,

來源:互聯網
上載者:User

hibernate設定檔,

 

 hibernate設定檔概要:

      與Hibernate相關的設定檔有:hibernate.cfg.xml,hibernate.properties,xxx.hbm.xml(實體類對應檔)等。Hibernate的:http://hibernate.org/orm/

目錄: hibernate設定檔

   1.hibernate設定檔的讀取順序  

      hibernate設定檔可以有兩種方式:官方推薦的XML設定檔和屬性設定檔。我們大都採用XML方式的配置,因為結構良好,配置靈活,可讀性強。而且可以在XML中直接配置對應檔而屬性檔案則不行。但是我們可能忽略的一個問題是:hibernate首先尋找的設定檔卻是屬性設定檔hibernate.properties。 
    看看下面這張圖,就很清楚了。 
 
    可以看到Hibernate首先去找了hibernate.properties設定檔,但是沒找到。然後建立位元組碼支援器,用到cglib,之後用了時間戳記控制,之後才是讀取hibernate.cfg.xml設定檔。這些在最前面的日誌資訊我們可能會忽略它,但是我們要明白hibernate的一些載入原理。既然Hibernate第一讀取的是屬性設定檔,那麼下面我們用屬性設定檔做一個例子來看看效果。 
 
    將XML檔案打成.bak,加入屬性設定檔,其中的配置和XML相同。 

hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver  hibernate.connection.url=jdbc:oracle:thin:@localhost:1521:orcl  hibernate.connection.username=hibernate  hibernate.connection.password=hibernate  hibernate.dialect=org.hibernate.dialect.OracleDialect  hibernate.current_session_context_class=thread  hibernate.show_sql=true  hibernate.format_sql=true  

 

    程式中,我們這樣寫就行了。 

package demo;  import java.util.Date;  import org.hibernate.*;  import org.hibernate.cfg.Configuration;  import demo.domain.User;  public class Test {      public static void main(String[] args) {          Configuration config = new Configuration();          config.addResource("demo/domain/User.hbm.xml");// 載入對應檔         // config.addClass(demo.domain.User.class); 另外一種載入方式          SessionFactory sessionFactory = config.buildSessionFactory();                     Session session = sessionFactory.getCurrentSession();          Transaction tx = session.beginTransaction();          User user = new User();          user.setName("Sarin");          user.setPhone("15912345678");          user.setDepartment("研發部");          user.setCity("大連");          user.setHireTime(new Date());          session.save(user);           tx.commit();      }  }  

 

    在控制台,我們就看到這樣的日誌資訊了。 
 
    可以看出,Hibernate直接讀取配置資訊,然後是位元組碼支援提供,初始化時間戳記,載入對應檔,後面的流程就是一樣的了。 
    hibernate.properties和hibernate.cfg.xml都是Hibernate解析設定檔時預設的命名方式,而且都必須放在類路徑的根目錄下,當然是不建議在使用時修改的,因為這就多此一舉。如果有人不喜歡這種命名方式,當然可以自訂名稱,不過此時你必須告訴Hibernate設定檔是哪個,可以如下方式進行,也是比較方便的。 

File file = new File("src/demo/hibernate.xml");  Configuration config = new Configuration();  config.configure(file);  

 

    同時,Hibernate支援在程式中設定新的屬性,比如我們在配置時不設定show_sql和format_sql兩個屬性,那麼在程式中也可以設定,如下進行即可。 

config.setProperty(Environment.SHOW_SQL, "true");  config.setProperty(Environment.FORMAT_SQL, "true");  

    所有Hibernate中可配置的屬性都是org.hibernate.cfg.Environment類中的一個靜態成員變數。這樣在程式中添加新的屬性了。 
    org.hibernate.cfg.Configuration類的作用就是解析配置資訊和映射資訊,之後建立SessionFactory對象,此時配置資訊都綁定在SessionFactory中,Configuration就沒有使用價值了。這部分的Hibernate源碼也是比較好理解的。 

 

2.hibernate.properties

hibernate.dialect=org.hibernate.dialect.MySQLDialecthibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialecthibernate.dialect=org.hibernate.dialect.MySQLMyISAMDialecthibernate.connection.driver_class=com.mysql.jdbc.Driverhibernate.connection.url=jdbc:mysql://localhost:3306/jdbchibernate.connection.username=roothibernate.connection.password=123123

註:在Hibernate核心軟體包中的project/etc目錄下,有一個hibernate.properties檔案,它提供了串連各種關聯式資料庫的配置代碼範例。

3.hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>      <property name="connection.url">jdbc:mysql://localhost:3306/jdbc</property>      <property name="connection.username">root</property>      <property name="connection.password">123123</property>      <mapping resource="edu/fjnu/hotelsys/domain/Hotel.hbm.xml"/>      <mapping resource="edu/fjnu/hotelsys/domain/Room.hbm.xml"/>    </session-factory></hibernate-configuration> 
xxx.hbm.xml(實體類對應檔)
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping package="edu.fjnu.hotelsys.domain">  <class name="Room" table="room">     <id name="roomId" column="room_id" type="java.lang.Integer">       <generator class="increment"/>     </id>     <property name="roomNo" column="room_no" type="java.lang.String" length="10" not-null="true"/>     <property name="roomType" column="room_type" type="java.lang.String" length="1" not-null="true"/>     <property name="roomStatus" column="room_status" type="java.lang.String" length="1" not-null="true"/>     <property name="roomMemo" column="room_memo" type="java.lang.String" length="200"/>     <property name="roomEquipStr" column="room_equip" type="java.lang.String" length="20"/>     <many-to-one name="hotel" class="Hotel" column="hotel_no" fetch="join"></many-to-one>       </class>  </hibernate-mapping>

 

註:當hibernate下載解壓完成之後,我們很容易在解壓之後的檔案夾中找到設定檔與對應檔的樣板範例,檔案中對.jar的架包也做了很好的分類。

   讀取設定檔

1.從 hibernate.cfg.xml 中載入配置,實體對應檔為xml格式

import org.hibernate.SessionFactory;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;public class HibernateUtil {        private static SessionFactory sessionFactory;        static{        try{            Configuration config = new Configuration().configure();            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(config.getProperties());            setSessionFactory(config.buildSessionFactory(builder.build()));        }catch(Exception e){            e.printStackTrace();        }    }            public static void shutdown(){        getSessionFactory().close();    }    public static SessionFactory getSessionFactory() {        return sessionFactory;    }    public static void setSessionFactory(SessionFactory sessionFactory) {        HibernateUtil.sessionFactory = sessionFactory;    }}

 

2.  從 hibernate.cfg.xml 中載入配置,載入@註解實體類,載入設定檔

import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;/* Hibernate官方提供的Hibernate工具類,主要作用就是返回一個Session。載入@註解配置的實體類需要使用 * @AnnotationConfiguration類。HibernateUtil類包含一個SessionFactory對象。該類初始化時會載入 * hibernate.cfg.xml,並初始化SessionFactory。通過SessionFactory可開啟Session會話,對實體類進行操作。*/public class HibernateUtil {    private static final SessionFactory sessionFactory;  // 單態模式的SessionFactory對象    static {                                             // static代碼塊,類載入時初始化Hibernate        try {            // 從 hibernate.cfg.xml 中載入配置,載入@註解實體類,載入設定檔            sessionFactory = new AnnotationConfiguration().configure(                    "hibernate.cfg.xml").buildSessionFactory();        } catch (Throwable ex) {            System.err.println("Initial SessionFactory creation failed." + ex);            throw new ExceptionInInitializerError(ex);        }    }    public static SessionFactory getSessionFactory() {  // 靜態方法,返回SessionFactory        return sessionFactory;    }}

 

解析:

Configuration類用來管理我們的設定檔的資訊的,通過它,我們可以通過建立一個configuration執行個體來管理相應的配置文檔,但是通常我們只建立一個configuration執行個體。 

在這裡,我們看到:要建立一個Configuration,可以使用

Configuration config = new Configuration().configure(); 

 

這裡我們要明白的是,Configuration是入口,通過它來獲得設定檔。 

同時Configuration還可以通過指定參數來傳遞: 
下面看:

File file = new File("c:\\Hibernate.xml"); Configuration config = new Configuration().config(file); 

 

同時,Configuration還有一些比較重要的方法:

addProperties(); setProperties(); 

 

下面看一下例子:

Properties properties = Porperties.load("a.properties"); Configuration configure = new Configuration().setProperties(properties); 

 

同時還可以指定.hbm.xml檔案,下面是幾種方法:

addClass(); addFile(); addURL(); 

 

下面看一下例子:

Configuration configure = new Configuration().addClass(Order.class); Configuration configure = new Configuration().addURL(Configuration.class.getResource(Order.hbm.xml)); Configuration configure = new Configuration().addFile("Order.hbm.xml"); 

 

下面簡單的看一下SessionFactory類 
首先看一下代碼

Configuration configure = new Configuration().configure(); SessionFactory sessions = configure.buildSessionFactory(); 

 

這裡要說明的是,SessionFactory是安全執行緒的,可以被多個線程調用。在我們實際開發中,我們可以在初始化的部分構造一個 SessionFactory即可,比如,在一個公用靜態類中初始化一個SessionFactory的readonly常量等等。它充當資料存放區源的代 理。這裡用到了原廠模式。需要注意的是SessionFactory並不是輕量級的,因為一般情況下,一個項目通常只需要一個 SessionFactory就夠,當需要操作多個資料庫時,可以為每個資料庫指定一個SessionFactory。   

參考文章:http://www.cnblogs.com/xiohao/p/4150293.html
http://www.cnblogs.com/black-snail/p/3767548.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.