# [Hibernate] Datenbankverbindung testen



## timomeinen (17. Okt 2006)

Hallo,

ich verwende Hibernate als OR-Mapper und möchte in meiner Swing-Anwendung testen, ob Hibernate eine Verbindung zur Datenbank aufbauen konnte. Hibernate baut die Verbindung zur DB in der Klasse SettingsFactory.java auf. Leider werden SQLExceptions einfach verworfen und nicht weitergegeben:


```
catch (SQLException sqle) { 
         log.warn("Could not obtain connection metadata", sqle); 
      }
```

Hat jemand eine Idee, wie ich trotzdem herausbekommen kann, ob die Verbindung zur DB beesteht? Muss ich mir etwa ne JDBC-Connection von Hibernate organisieren?


Falls die DB beispielsweise nicht läuft quittiert Hibernate dies hiermit:


```
20:11:29,202  WARN SettingsFactory:103 - Could not obtain connection metadata 
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: 

** BEGIN NESTED EXCEPTION ** 

java.net.SocketException 
MESSAGE: java.net.ConnectException: Connection refused 

STACKTRACE: 

java.net.SocketException: java.net.ConnectException: Connection refused
```

Danke und Gruss
Timo Meinen
timomeinen@gmail.com


----------



## KSG9|sebastian (17. Okt 2006)

Hibernate nützt dafür eigene Exceptions. Fang einfach mal alles per catch(Exception .) ab und schau von welchem Typ die Exceptions sind. Oder schau in die API was die Hibernateklasse beim Initialisieren der Sessionfactory alles wirft.


----------



## timomeinen (17. Okt 2006)

Genau das ist das Problem:

Hibernate "verpackt" diese Exceptions, aber wirft *keine* eigene. Siehe mein Beispiel von Oben: "Nested Exception is....".

Auch im Log-Level ist es lediglich "WARN". :-(

Gruß
Timo


----------



## KSG9|sebastian (18. Okt 2006)

Ich bezweifel dass Hibernate einfach die Exception frisst...hatte selbst nie ein Problem damit.


----------



## KSG9|sebastian (18. Okt 2006)

Wenn du die SessionFactory (respektive SessionFactoryImpl) erzeugst (SessionFactory#openSession) dann wirft Hibernate sehr wohl ne Exception, und zwar vom Typ HibernateException.
Siehe hier:
http://www.hibernate.org/hib_docs/v3/api/



			
				Hibernate API hat gesagt.:
			
		

> Description copied from interface: SessionFactory
> Create database connection and open a Session on it.
> 
> Specified by:
> ...


Das ist genau das was du willst. Exception beim öffnen der Verbindung abfangen => catch(HibernateException ex)


----------



## timomeinen (18. Okt 2006)

Hallo,

Hibernate verwirft die SQLException und stellt auch *keine* eigene Exception. Hier ein Beispielprogramm, bei dessen Ausführung ich die Datenbank nicht starte, damit definitv ein Fehler auftritt:


```
public Main() {
        try {
            // Load Hibernate
            HibernateUtil.getSession();
        } catch (Exception e) {
            System.out.println("TEST: Fehler in Hibernate");
            e.printStackTrace();
            System.exit(1);
        }
    }
```

Das Programm wird nach dem Fehler nicht abgebrochen. Der Catch-Block wird gar nicht erreicht, obwohl es eine *Nested Exception* gibt. Die SettingsFactory gibt lediglich eine *WARN*-Meldung aus, führt das Programm aber weiter aus:


```
12:01:48,255  WARN SettingsFactory:103 - Could not obtain connection metadata
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: 

** BEGIN NESTED EXCEPTION ** 

java.net.SocketException
MESSAGE: java.net.ConnectException: Connection refused
```

Im Sourcecode von Hibernate wird eine SQLException in der SettingsFactory.java einfach "vergessen":


```
catch (SQLException sqle) { 
         log.warn("Could not obtain connection metadata", sqle); 
      }
```


Anschliessend noch die Ausgabe des Testprogrammes. Wie ihr sehen könnt, wird das Programm nach der SocketException nicht abgebrochen, sondern fortgesettz. :-(

Danke für eure Hilfe
Timo Meinen


```
[size=8]compile:
run:
12:01:45,103  INFO Environment:479 - Hibernate 3.1.3
12:01:45,132  INFO Environment:509 - hibernate.properties not found
12:01:45,139  INFO Environment:525 - using CGLIB reflection optimizer
12:01:45,146  INFO Environment:555 - using JDK 1.4 java.sql.Timestamp handling
12:01:45,334  INFO Configuration:1308 - configuring from resource: /hibernate.cfg.xml
12:01:45,336  INFO Configuration:1285 - Configuration resource: /hibernate.cfg.xml
12:01:45,698  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/base/hibernate/ObjectBase.hbm.xml
12:01:46,042  INFO HbmBinder:309 - Mapping class: org.jclubmanager.model.base.ObjectBase -> objectbase
12:01:46,087  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/typeDescription/hibernate/TypeDescription.hbm.xml
12:01:46,269  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.typeDescription.TypeDescription -> type_description
12:01:46,299  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/contacts/hibernate/City.hbm.xml
12:01:46,561  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.contacts.City -> city
12:01:46,564  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/contacts/hibernate/Communication.hbm.xml
12:01:46,631  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.contacts.Communication -> communication
12:01:46,852  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/contacts/hibernate/ContactAdress.hbm.xml
12:01:46,895  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.contacts.ContactAdress -> contactadress
12:01:46,899  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/contacts/hibernate/Contact.hbm.xml
12:01:46,992  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.contacts.Contact -> contact
12:01:47,006  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/members/hibernate/Person.hbm.xml
12:01:47,218  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.members.Person -> person
12:01:47,221  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/members/hibernate/NaturalPerson.hbm.xml
12:01:47,271  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.members.NaturalPerson -> natural_person
12:01:47,275  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/members/hibernate/Member.hbm.xml
12:01:47,316  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.members.Member -> member
12:01:47,325  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/club/hibernate/Club.hbm.xml
12:01:47,369  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.club.Club -> club
12:01:47,373  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/licence/hibernate/Licence.hbm.xml
12:01:47,422  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.licence.Licence -> licence
12:01:47,426  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/aircraft/hibernate/Aircraft.hbm.xml
12:01:47,522  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.aircraft.Aircraft -> aircraft
12:01:47,526  INFO HbmBinder:1397 - Mapping collection: org.jclubmanager.model.aircraft.Aircraft.owner -> aircraft_owner
12:01:47,530  INFO Configuration:469 - Reading mappings from resource: org/jclubmanager/model/aircraft/hibernate/AircraftType.hbm.xml
12:01:47,563  INFO HbmBinder:804 - Mapping union-subclass: org.jclubmanager.model.aircraft.AircraftType -> aircraft_type
12:01:47,593  INFO Configuration:1419 - Configured SessionFactory: null
12:01:47,739  INFO HbmBinder:2349 - Mapping collection: org.jclubmanager.model.contacts.Contact.communications -> communication
12:01:47,744  INFO HbmBinder:2349 - Mapping collection: org.jclubmanager.model.contacts.Contact.ContactAdress -> contactadress
12:01:47,747  INFO HbmBinder:2349 - Mapping collection: org.jclubmanager.model.members.Member.licences -> licence
12:01:47,795  INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
12:01:47,830  INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 20
12:01:47,832  INFO DriverManagerConnectionProvider:45 - autocommit mode: false
12:01:47,852  INFO DriverManagerConnectionProvider:80 - using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost/jcm
12:01:47,854  INFO DriverManagerConnectionProvider:86 - connection properties: {user=club, password=****}
12:01:48,255  WARN SettingsFactory:103 - Could not obtain connection metadata
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: 

** BEGIN NESTED EXCEPTION ** 

java.net.SocketException
MESSAGE: java.net.ConnectException: Connection refused

STACKTRACE:

java.net.SocketException: java.net.ConnectException: Connection refused
        at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:284)
        at com.mysql.jdbc.Connection.createNewIO(Connection.java:2555)
        at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
        at java.sql.DriverManager.getConnection(DriverManager.java:525)
        at java.sql.DriverManager.getConnection(DriverManager.java:140)
        at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
        at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:72)
        at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)
        at org.jclubmanager.model.base.hibernate.HibernateUtil.<clinit>(HibernateUtil.java:41)
        at org.jclubmanager.view.main.Main.<init>(Main.java:70)
        at org.jclubmanager.view.main.Main$5.run(Main.java:256)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)


** END NESTED EXCEPTION **



Last packet sent to the server was 55 ms ago.
        at com.mysql.jdbc.Connection.createNewIO(Connection.java:2621)
        at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
        at java.sql.DriverManager.getConnection(DriverManager.java:525)
        at java.sql.DriverManager.getConnection(DriverManager.java:140)
        at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
        at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:72)
        at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)
        at org.jclubmanager.model.base.hibernate.HibernateUtil.<clinit>(HibernateUtil.java:41)
        at org.jclubmanager.view.main.Main.<init>(Main.java:70)
        at org.jclubmanager.view.main.Main$5.run(Main.java:256)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
12:01:48,578  INFO Dialect:103 - Using dialect: org.hibernate.dialect.MySQLDialect
12:01:48,597  INFO TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
12:01:48,608  INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA
 environment, use of read-write or transactional second-level cache is not recommended)
12:01:48,610  INFO SettingsFactory:125 - Automatic flush during beforeCompletion(): disabled
12:01:48,614  INFO SettingsFactory:129 - Automatic session close at end of transaction: disabled
12:01:48,620  INFO SettingsFactory:144 - Scrollable result sets: disabled
12:01:48,634  INFO SettingsFactory:152 - JDBC3 getGeneratedKeys(): disabled
12:01:48,640  INFO SettingsFactory:160 - Connection release mode: auto
12:01:48,646  INFO SettingsFactory:184 - Maximum outer join fetch depth: 2
12:01:48,648  INFO SettingsFactory:187 - Default batch fetch size: 1
12:01:48,653  INFO SettingsFactory:191 - Generate SQL with comments: disabled
12:01:48,655  INFO SettingsFactory:195 - Order SQL updates by primary key: disabled
12:01:48,657  INFO SettingsFactory:338 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
12:01:48,665  INFO ASTQueryTranslatorFactory:24 - Using ASTQueryTranslatorFactory
12:01:48,667  INFO SettingsFactory:203 - Query language substitutions: {}
12:01:48,668  INFO SettingsFactory:209 - Second-level cache: enabled
12:01:48,670  INFO SettingsFactory:213 - Query cache: disabled
12:01:48,672  INFO SettingsFactory:325 - Cache provider: org.hibernate.cache.EhCacheProvider
12:01:48,681  INFO SettingsFactory:228 - Optimize cache for minimal puts: disabled
12:01:48,683  INFO SettingsFactory:237 - Structured second-level cache entries: disabled
12:01:48,702  INFO SettingsFactory:264 - Statistics: disabled
12:01:48,704  INFO SettingsFactory:268 - Deleted entity synthetic identifier rollback: disabled
12:01:48,706  INFO SettingsFactory:283 - Default entity-mode: pojo
12:01:48,791  INFO SessionFactoryImpl:154 - building session factory
12:01:48,800 DEBUG CacheManager:191 - Creating new CacheManager with default config
12:01:48,810 DEBUG CacheManager:164 - Configuring ehcache from classpath.
12:01:48,818  WARN Configurator:126 - No configuration found. Configuring ehcache from ehcache-failsafe.xml 
found in the classpath: jar:file:/home/timo/development/jclubmanager%20cvs/Core/lib/hibernate/ehcache-1.1.jar!/
ehcache-failsafe.xml
12:01:48,841 DEBUG Configuration$DiskStore:185 - Disk Store Path: /tmp
12:01:51,181  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
12:01:55,434  INFO Main:241 - Disconnecting from Database
BUILD SUCCESSFUL (total time: 13 seconds)[/size]
```


----------



## KSG9|sebastian (18. Okt 2006)

Was liefert Session#isClosed() zurück?


----------



## timomeinen (18. Okt 2006)

Hallo,

ein *isClosed* gibt es bei der Session nicht, aber *isConnected* und *isOpen*. Beide geben true zurück. Sehr komisch.

Ich habe das Beispielprogramm auf ein Minimum reduziert. Selbes Problem:


```
public static void main(String[] args) {
        try {
            Configuration conf = new Configuration().configure();
            SessionFactory sessionFactory = conf.buildSessionFactory();
            Session session = sessionFactory.openSession();
            System.out.println("Session: Connected:" + session.isConnected());
            System.out.println("Session: Open:" + session.isOpen());
            session.close();
            System.out.println("Test beendet");
        } catch (Exception e) {
            System.out.println("Fehler in Hibernate");
            e.printStackTrace();
        }
```

Auch hier kommt das Programm nicht in den Catch-Block.



```
...
13:43:05,611 DEBUG Configuration$DiskStore:185 - Disk Store Path: /tmp
13:43:07,937  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
Session: Connected:true
Session: Open:true
Test beendet
```


----------



## KSG9|sebastian (18. Okt 2006)

Das ist verdammt komisch. Welche Hibernateversion verwendest du?


----------



## SlaterB (18. Okt 2006)

reicht es allgemein gesehen nicht, ein in der DB vorhandes Objekt testweise zu laden?
wenn nicht zurückgegeben dann keine DB-Verbindung da


----------



## timomeinen (18. Okt 2006)

Hibernate Version 3.1.3

Den Umweg über den Datensatz haben wir auch schon getestet. Ist aber keine schöne Lösung.

Ich denke, dass das Problem im Source von Hibernate steckt (siehe Codeschnipsel oben). 

Danke
Timo


----------



## KSG9|sebastian (18. Okt 2006)

Das ist echt sehr verwunderlich. Die Exception wird einfach abgefangen, mehr nicht. Hab grade den Code im SVN durchwühlt aber nichts nützliches gefunden.
Den Hibernatecode kopieren und die Exception weiterleiten (werfen). Ist halt nicht sehr sauber. Wenn ein Update kommt funktioniert der Code unter Umständen nimmer.
Ansonsten versuchen mittels JDBC ne Verbindung aufzubauen. Bei Erfolg -> SessionFactory öffnen
Bei Fehler -> Programm stoppen


----------

