You are on page 1of 2

package com.ATBoscoCastellano.Util.

HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
@SuppressWarnings("deprecation")
public class HibernateUtil {
public static final SessionFactory sessionFactory = buildSessionFactory();
// private static Session session = null;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
// return new AnnotationConfiguration().configure().buildSessionFacto
ry();
return new Configuration().configure("hibernate.cfg.xml").buildSessi
onFactory();
}
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;
}
public static Session beginSession (){
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
return session;
}
public static void endSession(Session session){
session.getTransaction().commit();
session.close();
}
public static boolean checkEntityExists(Class clazz, String identifierKey, O
bject identifierValue) throws HibernateException {
Session session = HibernateUtil.beginSession();
boolean result = session.createCriteria(clazz)
.add(Restrictions.eq(identifierKey, identifierValue))
.setProjection(Projections.property(identifierKey))
.uniqueResult() != null;
HibernateUtil.endSession(session);
return result;
}

}
~

You might also like