Configuration cfg = new Configuration().configure();
Configuration
Configuration 类的作用是对Hibernate 进行配置,以及对它进行启动。在Hibernate 的启动过程中,Configuration 类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象。虽然Configuration 类在整个Hibernate 项目中只扮演着一个很小的角色,但它是启动hibernate 时所遇到的第一个对象。
■作用:加载核心配置文件
▲hibernate.properties
Configuration cfg = new Configuration();
▲hibernate.cfg.xml
■加载映射文件
//手动加载
configuration.addResource("com/test/customer.hbm.xml");
hibernate.cfg.xml 里配置
<mapping resource="com/test/customer.hbm.xml" />
SessionFactory:Session工厂
SessionFactory接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。
SessionFactory内部维护了Hibernate的连接池和Hibernate的二级缓存。是线程安全的对象。一个项目创建一个对象即可。
■在hibernate.cfg.xml中配置C3P0连接池
<!-- 配置C3P0连接池 -->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!--在连接池中可用的数据库连接的最少数目 -->
<property name="c3p0.min_size">5</property>
<!--在连接池中所有数据库连接的最大数目 -->
<property name="c3p0.max_size">10</property>
<!--设定数据库连接的过期时间,以秒为单位,
如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
<property name="c3p0.timeout">120</property>
<!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
<property name="c3p0.idle_test_period">3000</property>
●抽取工具类
工具类 hibernateUtils:
package com.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Hibernate的工具类
* @author jt
*
*/
public class hibernateUtils {
public static final Configuration cfg;
public static final SessionFactory sf;
static{
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
}
public static Session openSession(){
return sf.openSession();
}
public static void closeSessionFactory(){
sf.close();
}
}
用法:
public void demo() {
Session seesion = hibernateUtils.openSession();
// 4.手动开启事务:
Transaction transaction = seesion.beginTransaction();
// 5.编写代码
Customer customer = new Customer();
customer.setCust_name("测试");
try {
Serializable id = seesion.save(customer);
System.out.println(id);
} catch (Exception e) {
System.out.println(e);
// TODO: handle exception
}
// 6.事务提交
transaction.commit();
// 7.资源释放
seesion.close();
hibernateUtils.closeSessionFactory();
}