67,513
社区成员
发帖
与我相关
我的任务
分享
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ThreadLocal<Session> threadLocal;
static{
try {
//创建工厂
Configuration cfg = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
} catch (HibernateException e) {
System.err.println(e.getMessage());
}
threadLocal = new ThreadLocal<Session>();
}
private HibernateUtil(){
}
// 获取Session
public static Session getSession()throws HibernateException{
Session session = threadLocal.get();
if(session==null){
if(sessionFactory==null){
System.out.println("sessionFactory为空!!!");
}
// 问题出在这里,openSession的时候报空指针,所以我在上面判断sessionFactory,
// 结果确实输出了 sessionFactory为空!!! 求解决sessionFactory 为什么创建失败?
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
// 关闭Session
public static void closeSession()throws HibernateException{
Session session = threadLocal.get();
if(session!=null){
session.close();
}
threadLocal.set(null);
}
}
public class Test {
Session session;
Transaction transaction;
@org.junit.Test
public void test(){
News news = new News("今晚武汉有雨","本报讯:预计今晚武汉地区局部有中到大雨,请注意防范",new Date());
System.out.println(news);
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
session.save(news);
transaction.commit();
HibernateUtil.closeSession();
}
}
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
/* 下面这段代码可能适用于4.0版本(未经测试)
* 下面的代码可以在4.1之后版本运行,但不被推荐使用
ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry ();
*/
// 创建SessionFactory实例
sessionFactory = configuration.buildSessionFactory(registry);
}
public static Session currentSession() {
return sessionFactory.openSession();
}
public static void closeSession(Session session) {
if (session != null) {
session.close();
}
}
}