hibernate 抽取工具类
编写工具类
package com.xmetc.hibernate.zyz;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static final Configuration cf;
private static final SessionFactory sf;
static {
cf=new Configuration().configure();
sf=cf.buildSessionFactory();
}
public static Session openSession() {
return sf.openSession();
}
}
提取前
@Test
public void demo1() {
//1.加载hibernate核心配置文件
Configuration configuration = new Configuration().configure();
//2.创建一个sessionFactory对象,类似于jdbc中的连接池
SessionFactory sessionFactory = configuration.buildSessionFactory();
//3.通过sessionFactory获取到session对象:类似于jdbc中的connect
Session session = sessionFactory.openSession();
//4.手动开启事务
Transaction transaction = session.beginTransaction();
//5.编写代码
MUser user = new MUser();
user.setUsername("张w11三");
user.setPassword("99999");
session.save(user);
//6.事务提交
transaction.commit();
//7.资源释放
session.close();
sessionFactory.close();
}
提取后
@Test
public void add2() {
Session session= HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
MUser user = new MUser();
user.setUsername("张w三");
user.setPassword("88888888888");
session.save(user);
transaction.commit();
session.close();
}