private SessionFactory _sessionFactory;
private Session _session;
private ThreadLocal _threadLocal = new ThreadLocal();
// Template Methods
protected abstract String getKeyFieldName();
protected abstract Class getStoredClass();
// Methods
protected AbstractServiceDBImpl() {
// initalizeHibernate();
if (! isHibernateInitialized())
initalizeHibernate();
}
protected Session getSession() throws HibernateException {
Contract.require(isHibernateInitialized(), "hibernate ist initialisiert");
Session session = (Session) _threadLocal.get();
if (session == null || !session.isOpen()) {
session = _sessionFactory.openSession();
_threadLocal.set(session);
}
/*try {
int i = 0;
System.out.println(">>> session.connection().isClosed() " + session.connection().isClosed());
} catch (HibernateException e) {
System.out.println("Probleme beim connect");
//e.printStackTrace();
} catch (SQLException e) {
System.out.println("Probleme beim connect");
//e.printStackTrace();
}*/
session.clear();
Contract.ensure(session != null, "result");
return session;
}
private boolean sessionIsConnected()
{
// return _session.isConnected();
return ((Session) _threadLocal.get()).isConnected();
}
protected boolean isHibernateInitialized() {
return _sessionFactory != null;
}
/**
* Hibernate initialisieren. SessionFactory merken.
*/
private void initalizeHibernate() {
Contract.require(!isHibernateInitialized(), "Hibernate is not initialized yet");
try
{
// Konfigurationsdateien einlesen
URL mappingURL = getClass().getClassLoader().getResource("mapping.xml");
InputStream in = getClass().getClassLoader().getResourceAsStream("hibernate.properties");
Properties properties = new Properties();
properties.load(in);
// Hibernate konfigurieren
Configuration configuration = new Configuration();
configuration.setProperties(properties);
configuration.addURL(mappingURL);
// SessionFactory merken! Sie erzeugt die benötigten Sessions.
_sessionFactory = configuration.buildSessionFactory();
}
catch (HibernateException e)
{
System.out.println("Probleme beim Konfigurieren von Hibernate!");
e.printStackTrace();
}
catch (IOException e)
{
System.out.println("Probleme beim Zugriff auf die Datei hibernate.properties");
e.printStackTrace();
}
Contract.ensure(isHibernateInitialized(), "Hibernate is successfully initialized");
}