淺談Hibernate XML配置文件
Hibernate有很多值得學(xué)習(xí)的地方,這里我們主要介紹Hibernate XML配置文件,包括介紹Hibernate Configuation類(lèi)等方面。
Hibernate XML配置文件
如果你覺(jué)得可以在容器之外使用現(xiàn)有的Hibernate對(duì)象的話,那你首先要做的事就是得自己手工管理所有的配置項(xiàng),在本文余下部分我所采用的方法是使用一個(gè)基于命令行的JAVA程序。既然你已經(jīng)配置了Hibernate XML配置文件,你應(yīng)該知道需要提供的參數(shù),例如JNDI DataSource名,實(shí)體映射文件,還有其他一些處理SQL日志的屬性。如果你想使用命令行程序的話,你就得解決如何解析XML文件和把它添加到配置項(xiàng)中的這些問(wèn)題。雖然解析XML文件也不難,但這本身并不是我們的重點(diǎn)。因此,我建議使用propetries文件,properties文件比較直觀而且容易加載并從中讀取數(shù)據(jù)。下面是配置Hibernate所需要的最小屬性集(不包括任何實(shí)體映射)。
- hibernate.dialect=net.sf.hibernate.dialect.PostgreSQLDialect
- hibernate.connection.driver_class=org.postgresql.Driver
- hibernate.connection.url=jdbc:postgresql://devserver/devdb
- hibernate.connection.username=dbuser
- hibernate.connection.password=dbpassword
- hibernate.query.substitutions yes 'Y'
正如你所看到的,上面的屬性值指定了數(shù)據(jù)庫(kù)方言,JDBC驅(qū)動(dòng),數(shù)據(jù)庫(kù)url,用戶名,用戶密碼,以及是否使用查找替換。只要定義以上幾項(xiàng)數(shù)值并保存在文件Hibernate.properties里(要放置在你的類(lèi)路徑里面哦),就能很輕松的加載,填充到Hibernate Configuation類(lèi)里面。
- Properties props = new Properties();
- try {
- props.load(props.getClass().getResourceAsStream("hibernate.properties"));
- }
- catch(Exception e){
- System.out.println("Error loading hibernate properties.");
- e.printStackTrace();
- System.exit(0);
- }
- String driver = props.getProperty("hibernate.connection.driver_class");
- String connUrl = props.getProperty("hibernate.connection.url");
- String username = props.getProperty("hibernate.connection.username");
- String password = props.getProperty("hibernate.connection.password");
- // In my examples, I use Postgres, but Hibernate
- // supports virtually every popular dbms out there.
- Class.forName("org.postgresql.Driver");
- Connection conn = DriverManager.getConnection(connUrl, username, password);
- Configuration cfg = new Configuration();
- cfg.setProperties( props );
- SessionFactory sessions = cfg.buildSessionFactory();
- Session session = sessions.openSession(conn);
【編輯推薦】