1. 程式人生 > >hibernate載入hibernate.cfg.xml檔案

hibernate載入hibernate.cfg.xml檔案

1、預設方式載入hibernate.cfg.xml檔案,編寫hibernate的操作類,通過Configuration cfg = new Configuration().configure("hibernate-c3p0.cfg.xml");載入指定配置檔案,並建立SessionFactory

package utils;

import org.hibernate.Session;  
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  
public class HibernateUtils {  
/* 
  *讀取Hibernate.cfg.xml檔案 
*/  
    private static SessionFactory factory;  
      
    static {
        try { 
            //讀取hibernate.cfg.xml檔案  
            Configuration cfg = new Configuration().configure("hibernate-c3p0.cfg.xml"); 
            //建立SessionFactory 
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();  
            factory = cfg.buildSessionFactory(serviceRegistry);
        }catch(Exception e) {  
            e.printStackTrace();  
        }  
    }  
    /* 
      *開啟Session 
    */  
      
    public static Session getSession() {  
        return factory.openSession();  
    }   
    /* 
      *關閉Session 
    */  
      
    public static void closeSession(Session session) {  
        if (session != null) {  
            if (session.isOpen()) {  
                session.close();  
            }  
        }  
    }  
      
    public static SessionFactory getSessionFactory() {  
        return factory;  
    }  
}  

2、hibernate整合到spring上,通過依賴注入例項化sessionfactory類
<!-- spring配置hibernate4 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 配置hibernate屬性,把資料庫連線的相關資訊放到此處配置,通過properties檔案載入 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${db.dialect}</prop>
				<prop key="hibernate.connection.driver_class">${db.driver_class}</prop>
				<prop key="hibernate.connection.url">${db.url}</prop>
				<prop key="hibernate.connection.username">${db.user}</prop>
				<prop key="hibernate.connection.password">${db.pwd}</prop>
			</props>
		</property>
		<!-- 預設配置檔案 -->
		<property name="configLocation">
			<value>classpath:hibernate-c3p0.cfg.xml</value>
		</property>
		<!-- 配置hibernate對映檔案的路徑,放到這裡配置mapping對映檔案,可以使用萬用字元 -->
        <property name="mappingLocations"> 
        	<value>classpath:entity/*.hbm.xml</value>
		</property>
	</bean>


因為是整合到spring上,需要新增spring相關的jar,org.springframework.orm.hibernate4.LocalSessionFactoryBean存在於以下依賴中
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-orm</artifactId>
	    <version>4.3.9.RELEASE</version>
	</dependency>

通過spring配置hibernate,其實可以完全拋棄掉hibernate.cfg.xml配置檔案,通過spring新增hibernate配置屬性以及連線池,這方面資料網上很多,此處不作講解