---
title: "HibernateUtil.java"
author: "BBjava"
date: "2011-09-20T10:51:53Z"
tags: []
categories: ["开源软件"]
slug: "hibernateutil-java"
draft: false
lastmod: "2011-09-20T10:51:53Z"
id: 1175693
url: "https://bbjava.iteye.com/blog/1175693"
---

官方很简单的HibernateUtil.java，可以针对自己的需求改进。

```java
package org.bbjava.funny.test;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure("org/bbjava/funny/test/cfg/hibernate.cfg.xml").buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}
```

对了，工具类大多都是静态的，为什么呢，留下这个问题来思考。