Code: 我常用的HibernateUtil类,嘿嘿
- public final class HibernateUtil{
- private static SessionFactory sessionFactory;
- private HibernateUtil(){
- }
- //初始化
- static{
- Configuration cfg = new Configuration();
- cfg.configure();
- sessionFactory = cfg.buildSessionFactory();
- }
- public static SessionFactory getSessionFactory(){
- return sessionFactory;
- }
- public static Session getSession(){
- return sessionFactory.openSession();
- }
- }
上面是单数据库的HibernateUtil,Hibernate.cfg.xml文件默认在classpath下(src文件夹下)。
我自己写了个可以解析多个Hibernate.cfg.xml文件,访问多个数据库的HibernateUtil类(这就意味着你的项目可以使用多个数据库啊,不过对于多个数据库的事务管理我还不清楚,还是有点问题):
Code:
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- public final class HbnUtil {// 根据hibernate.cfg.xml创建一个静态sessionFactory
- private static SessionFactory sf;
- private static SessionFactory MSsf;
- static {
- try {
- sf = new Configuration().configure("/hbn-sqlserver.cfg.xml")
- .buildSessionFactory();
- MSsf = new Configuration().configure("/hbn-mysql.cfg.xml")
- .buildSessionFactory();
- } catch (Exception e) {
- System.err.println("%%%% Error Creating SessionFactory %%%%");
- e.printStackTrace();
- }
- }
- public static SessionFactory getSessionFactory() {
- return sf;
- }
- public static Session getSession() {
- Session s = null;
- if (!sf.isClosed())
- s = sf.openSession();
- return s;
- }
- public static Session getSessionByDB(String DBName) {// 根据DBName判断
- Session s = null;
- if ("mysql".equals(DBName.toLowerCase())) {
- if (!MSsf.isClosed())
- s = MSsf.openSession();
- } else if ("sqlserver".equals(DBName.toLowerCase())) {
- if (!sf.isClosed())
- s = sf.openSession();
- } else {
- System.out.println("错误的 DBName!");
- }
- return s;
- }
- public static void closeSessionFactory() {
- if (!sf.isClosed()) {
- sf.close();
- }
- }
- public static void closeSessionFactoryByDB(String DBName) {
- if ("mysql".equals(DBName.toLowerCase())) {
- if (!MSsf.isClosed()) {
- MSsf.close();
- }
- } else if ("sqlserver".equals(DBName.toLowerCase())) {
- if (!sf.isClosed()) {
- sf.close();
- }
- } else {
- System.out.println("错误的 DBName!");
- }
- }
- }