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配置属性以及连接池,这方面资料网上很多,此处不作讲解