標籤:blog http io ar os 使用 sp for java
hibernate.properties和hibernate.cfg.xml部落格分類:
HibernateXMLSQLOracleJDBC hibernate設定檔可以有兩種方式:官方推薦的XML設定檔和屬性設定檔。我們大都採用XML方式的配置,因為結構良好,配置靈活,可讀性強。而且可以在XML中直接配置對應檔而屬性檔案則不行。但是我們可能忽略的一個問題是:hibernate首先尋找的設定檔卻是屬性設定檔hibernate.properties。
看看下面這張圖,就很清楚了。
可以看到Hibernate首先去找了hibernate.properties設定檔,但是沒找到。然後建立位元組碼支援器,用到cglib,之後用了時間戳記控制,之後才是讀取hibernate.cfg.xml設定檔。這些在最前面的日誌資訊我們可能會忽略它,但是我們要明白hibernate的一些載入原理。既然Hibernate第一讀取的是屬性設定檔,那麼下面我們用屬性設定檔做一個例子來看看效果。
將XML檔案打成.bak,加入屬性設定檔,其中的配置和XML相同。
Java代碼
- 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
程式中,我們這樣寫就行了。
Java代碼
- 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設定檔是哪個,可以如下方式進行,也是比較方便的。
Java代碼
- File file = new File("src/demo/hibernate.xml");
- Configuration config = new Configuration();
- config.configure(file);
同時,Hibernate支援在程式中設定新的屬性,比如我們在配置時不設定show_sql和format_sql兩個屬性,那麼在程式中也可以設定,如下進行即可。
Java代碼
- 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源碼也是比較好理解的。
歡迎交流,希望對使用者有用。
hibernate.properties和hibernate.cfg.xml