package cn.hibernate; import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; /**
* 创建一个工厂类 用于创建SessionFactory唯一的一个
*/
public class SessionFactoryUtils {
private static SessionFactory sessionFactory;
// 在静态的代码块中创建这个对象
static {
// 1:创建Configuration对象,用于读取hibernate.cfg.xml文件
Configuration config = new Configuration();
// 默认读取hibernte.cfg.xml
config.configure();
// 2:创建SessionFactory对象
sessionFactory = config.buildSessionFactory();
}
//3:提供一个静态的方法-返回SessionFactory的实例
public static SessionFactory getSessionFatory(){
return sessionFactory;
}
} 步4:测试是否连接数据库成功 – 获取 Connection对象
@Test
public void test1() {
// 1:获取 SessionFactory
SessionFactory sf = SessionFactoryUtils.getSessionFatory();
// 打开一个新的连接会话
Session session = sf.openSession();//
// 通过doWork获取一个COnnection,则所有在execute里面执行的方法都被Session控制
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
System.err.println("连接是:" + connection);
}
});
session.close();
}
package cn.hibernate;
import
org.hibernate.SessionFactory;
import
org.hibernate.cfg.Configuration;
/**
* 创建一个工厂类用于创建SessionFactory唯一的一个
*/
publicclass SessionFactoryUtils {
privatestatic SessionFactory sessionFactory;
// 在静态的代码块中创建这个对象
static {
// 1:创建Configuration对象,用于读取hibernate.cfg.xml文件
Configuration config = new Configuration();
// 默认读取hibernte.cfg.xml
config.configure();
// 2:创建SessionFactory对象
sessionFactory = config.buildSessionFactory();
}
//3:提供一个静态的方法-返回SessionFactory的实例
publicstatic SessionFactory getSessionFatory(){
returnsessionFactory;
}
}
步4:测试是否连接数据库成功 – 获取 Connection对象
@Test
publicvoid test1() {
// 1:获取 SessionFactory
SessionFactory sf = SessionFactoryUtils.getSessionFatory();
// 打开一个新的连接会话
Session session = sf.openSession();//
// 通过doWork获取一个COnnection,则所有在execute里面执行的方法都被Session控制
session.doWork(new Work() {
@Override
publicvoid execute(Connection connection) throws SQLException {
System.err.println("连接是:" + connection);
}
});
session.close();
}