因为每次用增删改查时都需要用到session,所以我们直接封装一个类,需要的时候只需要调用即可
package com.itnba.maya.bean;
import org.hibernate.*;
import org.hibernate.cfg.*;
import javafx.util.*;
public class HibernateUtil {
//定义常量是为了实现单例,不让随便new
private static final SessionFactory factory = BuilderFactory();
//ThreadLocal<Session>不是集合,是线程锁,为了单线程安全
private static final ThreadLocal<Session> threadlocal = new ThreadLocal<Session>();
private static SessionFactory BuilderFactory() {
Configuration conf = new Configuration().configure();
return conf.buildSessionFactory();
}
public static Session getSession(){
//先获取线程锁中的session
Session session = threadlocal.get();
if(session == null){
//如果没有session就新建一个session赋值给threadlocal
session = factory.openSession();
threadlocal.set(session);
}
return session;
}
public static void closeSession(){
//先获取线程锁中的session
Session session = threadlocal.get();
if(session != null){
//将session关闭之后再给threadlocal赋个null,方便其他线程使用
session.close();
threadlocal.set(null);
}
}
}
我们引用看一下能不能使用
package com.itnba.maya.bean;
import org.hibernate.*;
public class TestFruit {
public static void main(String[] args) {
Fruit f = new Fruit();
f.setIds("i001");
f.setName("西瓜");
f.setPrice(10.0);
f.setSource("张店");
f.setNumbers(100);
f.setImage("无");
try{
Session session = HibernateUtil.getSession();
session.beginTransaction();
session.save(f);
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
}
finally {
HibernateUtil.closeSession();
}
}
}
运行一下看下结果:
看下数据库中是否改变
这样我们就成功的将hibernate 初始化类封装好了,可以在需要时直接引用即可