Java tutorial
/* * @(#)HibernateUtil.java * * Copyright (c) 2013 Eugene Simakin <john-24@list.ru> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ex.util; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; /** * This class contains Hibernate Utilities. * @author ESimakin <john-24@list.ru> * */ public class HibernateUtil { private static SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; private static SessionFactory configureSessionFactory() throws HibernateException { try { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } /** * Returns SessionFactory object that you can use for create Session instances. * @return Session Factory object */ public static SessionFactory getSessionFactory() { configureSessionFactory(); return sessionFactory; } }