Configuration:创建hibernate配置对象,读取hibernate.cfg.xml文件初始化环境。
ServiceRegistry:注册hibernate属性的信息
SessionFactory:session工程类,这个类是一个重量级的对象,线程安全的,负责创建session,这个对象在服务器启动的时候创建一个即可。
Session:是一次和数据库的会话,但是不一定是一次连接,Session给我们提供很多操作数据库的方法,操作的是对象,影响的是数据库。
Transaction:事务对象,控制我们Session对数据库操作的事务。
package test;
import model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import org.hibernate.service.ServiceRegistry;
import java.util.Date;
public class Testhebernate {
@Test
public void test(){
// 创建hibernate配置对象
Configuration cfg = new Configuration();
// 配置核心文件的位置
cfg.configure("hibernate.cfg.xml");
// 注册配置属性信息
ServiceRegistry sr = (ServiceRegistry) new StandardServiceRegistryBuilder().
applySettings(cfg.getProperties()).build();
// 创建SessionFactory
SessionFactory factory = cfg.buildSessionFactory(sr);
// 创建Session会话
Session session = factory.openSession();
// 开启事务
Transaction tx = session.beginTransaction();
// 创建对象
User user = new User();
// user.setUserId(2);
user.setUname("你xx");
user.setGender("男");
user.setBirthday(new Date());
// 通过Session保存对象
session.save(user);
// 提交事务
tx.commit();
session.close();
factory.close();
}
}
封装成utils:
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;
public class HibernateUtils {
private static SessionFactory sf;
static {
// 创建hibernate配置对象
Configuration cfg = new Configuration();
// 配置核心文件的位置
cfg.configure("hibernate.cfg.xml");
// 注册配置属性信息
ServiceRegistry sr = (ServiceRegistry) new StandardServiceRegistryBuilder().
applySettings(cfg.getProperties()).build();
// 创建SessionFactory
sf = cfg.buildSessionFactory(sr);
}
public static SessionFactory getSessionFactory() {
return sf;
}
public static Session getSssion() {
return sf.openSession();
}
public static void closeSession (Session session) {
session.close();
}
public static void closeResource (Session session) {
session.close();
sf.close();
}
}