Kompilierfrage

Status
Nicht offen für weitere Antworten.
J

Javalearner

Gast
Hallo zusammen,

ich habe Ausgangssituation: Ich möchte per Hibernate einen Datenbankeintrag machen. Beim normalen Start der Testklasse wird kein Eintrag in die Datenbank erzeugt.

Hier der Code der Testklasse (auf das Wesentliche gekürzt):
Code:
package de.laliluna.example;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
* @author laliluna
*
*/
public class TestClient
{
  public static void main(String[] args)
  {
    createHoney();
  }
  private static Integer createHoney()
  {
    Session session = null;
    Transaction tx = null;
    Logger log = Logger.getLogger("TestClient");
    log.info("creating honey");
    // [laliluna] our returned primary key
    Integer id = null;
    try
    {
      // [laliluna] get the session from the factory
      session = HibernateSessionFactory.currentSession();
      // [laliluna] always start a transaction before doing something
      // (even reading) from the database
      tx = session.beginTransaction();
      // [laliluna] create a new object
      Honey honey = new Honey();
      honey.setName("Sebastian's favourite honey");
      honey.setTaste("sweet");
      // [laliluna] save it to the database, Hibernate returns your object
      // with the primary key field updated!
      System.out.println("----Speichern beginnt!----");
      id = (Integer) session.save(honey);
      System.out.println("----Speichern Ende!----");
      // [laliluna] commit your transaction or nothing is wrote to the db
      System.out.println("----Commit beginnt!----");
      tx.commit();
      System.out.println("----Ende des Commits!----");
      System.out.println("----Schließen beginnt!----");
      // [laliluna] clean up (close the session)
      session.close();
      System.out.println("----Ende des Schließens!----");
    } 
    catch (HibernateException e)
    {
      // [laliluna] when an error occured, try to rollback your
      // transaction
      if (tx != null)
        try
      {
          tx.rollback();
      } 
      catch (HibernateException e1)
      {
        log.warn("rollback not successful");
      }
      /*
       * [laliluna] close your session after an exception!! Your session
       * is in an undefined and unstable situation so throw it away!
       *
       */
      if (session != null)
        try
      {
          session.close();
      }
      catch (HibernateException e2)
      {
        log.warn("session close not successful");
      }
    }
    return id;
  }

Wenn ich jetzt einen Breakpoint zu Beginn von "createHoney()" setze und ich das Testprogramm debugge, läuft alles fehlerfrei bis zur letzten Zeile der main()-Methode. Der Fehler entsteht also in der geschweiften Klammer "}":

Code:
public static void main(String[] args)
  {
    createHoney();
  }

In dem Debugmodus kann ich folgende Information entnehmen:
Thread[main] ausgesetzt
Thread.exit() Zeile: nicht verfügbar
"Die Quelle wurde nicht gefunden".
Anschließend breche ich den Debugmodus ab.

Komischerweise wird der Datensatz beim Debuggen in die Datenbank geschrieben, beim "normalen" Ausführen jedoch nicht.
Meine Frage: Wird erst der Datensatz beim Beenden in die Datenbank geschrieben? Ich kann es mir nur schwer vorstellen, weil die Methode fehlerfrei durchläuft. Oder woran könnte es noch liegen?
 

MarcoBehnke

Bekanntes Mitglied
weil du das debuggen abgerbochen hast vermute ich, ansonsten wäre wohl bei der Ausführung später das rollback ausgeführt worden und der eintrag wäre wieder weg gewesen.

Debugge das mal bis zum Ende und schau vor allem mal, was im log4j log steht.

hinter dem ersten

catch (HibernateException e)
{

würde ich auch noch einen Logeintrag erzeugen, um zu sehen, ob Du da reingekommen bist. Gib außerdem die Exception auch ans log weiter, damit du auch die Info hast!

log.warn("Meldung", e);
 
J

Javalearner

Gast
Leider komme ich an dieser Stelle nicht weiter, weil die Fehlermeldung immer wieder auftaucht. Wie kann ich denn die Quelldatei dafür angeben? Ich habe bereits erfahren, dass man .class-Dateien als "normaler Mensch" gar nicht lesen kann.
 

MarcoBehnke

Bekanntes Mitglied
ich versteh grad nicht, was Du meinst..... ich habe mal deinen code von oben so verändert, dass er etwas gesprächiger ist. Anschließend sollte der Logoutput informativer sein. POste dann bitte einmal alles, was in der Console zu lesen war

Code:
package de.laliluna.example;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
* @author laliluna
*
*/
public class TestClient
{
  public static void main(String[] args)
  {
    createHoney();
  }
  private static Integer createHoney()
  {
    Session session = null;
    Transaction tx = null;
    Logger log = Logger.getLogger("TestClient");
    log.info("creating honey");
    // [laliluna] our returned primary key
    Integer id = null;
    try
    {
      // [laliluna] get the session from the factory
      session = HibernateSessionFactory.currentSession();
      // [laliluna] always start a transaction before doing something
      // (even reading) from the database
      tx = session.beginTransaction();
      // [laliluna] create a new object
      Honey honey = new Honey();
      honey.setName("Sebastian's favourite honey");
      honey.setTaste("sweet");
      // [laliluna] save it to the database, Hibernate returns your object
      // with the primary key field updated!
      System.out.println("----Speichern beginnt!----");
      id = (Integer) session.save(honey);
      System.out.println("----Speichern Ende!----");
      // [laliluna] commit your transaction or nothing is wrote to the db
      System.out.println("----Commit beginnt!----");
      tx.commit();
      System.out.println("----Ende des Commits!----");
      System.out.println("----Schließen beginnt!----");
      // [laliluna] clean up (close the session)
      session.close();
      System.out.println("----Ende des Schließens!----");
    }
    catch (HibernateException e)
    {
      log.error("Fehler", e); // das ist neu!
      // [laliluna] when an error occured, try to rollback your
      // transaction
      if (tx != null)
        try
      {
          tx.rollback();
      }
      catch (HibernateException e1)
      {
        log.warn("rollback not successful", e1);
      }
      /*
       * [laliluna] close your session after an exception!! Your session
       * is in an undefined and unstable situation so throw it away!
       *
       */
      if (session != null)
        try
      {
          session.close();
      }
      catch (HibernateException e2)
      {
        log.warn("session close not successful", e2);
      }
    }
    return id;
  }
 
J

Javalearner

Gast
Weil der catch()-Block gar nicht erst durchlaufen wird, so wird der Fehler auch nicht geloggt. Hier aber die vollständige Ausgabe:
Code:
0    [main] INFO  TestClient  - creating honey
62   [main] INFO  org.hibernate.cfg.Environment  - Hibernate 3.1
62   [main] INFO  org.hibernate.cfg.Environment  - hibernate.properties not found
78   [main] INFO  org.hibernate.cfg.Environment  - using CGLIB reflection optimizer
78   [main] INFO  org.hibernate.cfg.Environment  - using JDK 1.4 java.sql.Timestamp handling
156  [main] INFO  org.hibernate.cfg.Configuration  - configuring from resource: /hibernate.cfg.xml
156  [main] INFO  org.hibernate.cfg.Configuration  - Configuration resource: /hibernate.cfg.xml
312  [main] INFO  org.hibernate.cfg.Configuration  - Reading mappings from resource: de/laliluna/example/Honey.hbm.xml
422  [main] INFO  org.hibernate.cfg.HbmBinder  - Mapping class: de.laliluna.example.Honey -> thoney
453  [main] INFO  org.hibernate.cfg.Configuration  - Configured SessionFactory: null
453  [main] INFO  org.hibernate.cfg.Configuration  - processing extends queue
453  [main] INFO  org.hibernate.cfg.Configuration  - processing collection mappings
453  [main] INFO  org.hibernate.cfg.Configuration  - processing association property references
453  [main] INFO  org.hibernate.cfg.Configuration  - processing foreign key constraints
531  [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - Using Hibernate built-in connection pool (not for production use!)
531  [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - Hibernate connection pool size: 1
531  [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - autocommit mode: false
562  [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - using driver: org.hsqldb.jdbcDriver at URL: jdbc:hsqldb:D:/tmp/firsthibernate
562  [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - connection properties: {user=sa, password=****}
906  [main] INFO  org.hibernate.cfg.SettingsFactory  - RDBMS: HSQL Database Engine, version: 1.8.0
906  [main] INFO  org.hibernate.cfg.SettingsFactory  - JDBC driver: HSQL Database Engine Driver, version: 1.8.0
922  [main] INFO  org.hibernate.dialect.Dialect  - Using dialect: org.hibernate.dialect.HSQLDialect
937  [main] INFO  org.hibernate.transaction.TransactionFactoryFactory  - Using default transaction strategy (direct JDBC transactions)
937  [main] INFO  org.hibernate.transaction.TransactionManagerLookupFactory  - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Automatic flush during beforeCompletion(): disabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Automatic session close at end of transaction: disabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - JDBC batch size: 15
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - JDBC batch updates for versioned data: disabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Scrollable result sets: enabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - JDBC3 getGeneratedKeys(): disabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Connection release mode: auto
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Default batch fetch size: 1
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Generate SQL with comments: disabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Order SQL updates by primary key: disabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
937  [main] INFO  org.hibernate.hql.ast.ASTQueryTranslatorFactory  - Using ASTQueryTranslatorFactory
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Query language substitutions: {}
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Second-level cache: enabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Query cache: disabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Cache provider: org.hibernate.cache.NoCacheProvider
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Optimize cache for minimal puts: disabled
937  [main] INFO  org.hibernate.cfg.SettingsFactory  - Structured second-level cache entries: disabled
953  [main] INFO  org.hibernate.cfg.SettingsFactory  - Echoing all SQL to stdout
953  [main] INFO  org.hibernate.cfg.SettingsFactory  - Statistics: disabled
953  [main] INFO  org.hibernate.cfg.SettingsFactory  - Deleted entity synthetic identifier rollback: disabled
953  [main] INFO  org.hibernate.cfg.SettingsFactory  - Default entity-mode: pojo
1000 [main] INFO  org.hibernate.impl.SessionFactoryImpl  - building session factory
1375 [main] INFO  org.hibernate.impl.SessionFactoryObjectFactory  - Not binding factory to JNDI, no JNDI name configured
1375 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate  - Running hbm2ddl schema update
1375 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate  - fetching database metadata
1390 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate  - updating schema
1390 [main] INFO  org.hibernate.cfg.Configuration  - processing extends queue
1390 [main] INFO  org.hibernate.cfg.Configuration  - processing collection mappings
1390 [main] INFO  org.hibernate.cfg.Configuration  - processing association property references
1390 [main] INFO  org.hibernate.cfg.Configuration  - processing foreign key constraints
1437 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - table found: PUBLIC.THONEY
1453 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - columns: [id, name, taste]
1453 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - foreign keys: []
1453 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - indexes: [sys_idx_46]
1453 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate  - schema update complete
1453 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - cleaning up connection pool: jdbc:hsqldb:D:/tmp/firsthibernate
1453 [main] INFO  org.hibernate.impl.SessionFactoryImpl  - Checking 0 named HQL queries
1453 [main] INFO  org.hibernate.impl.SessionFactoryImpl  - Checking 0 named SQL queries
----Speichern beginnt!----
Hibernate: insert into thoney (name, taste, id) values (?, ?, null)
Hibernate: call identity()
----Speichern Ende!----
----Commit beginnt!----
----Ende des Commits!----
----Schließen beginnt!----
----Ende des Schließens!----
Ende

Leider kann ich dem keine entscheidende Information entnehmen.
 
G

Gast

Gast
Hallo,

Du benutzt HSQL als DB oder ?

Dies ist eine InMemory DB, d.h. nach Beendigung des Severs ist auch die DB weg!

Man kann wenn ich mich richtig erinnere die DB so einstellen, das Sie auch Persistent funktioniert. Aber da bin ich kein Experte.
 
J

Javalearner

Gast
Ja ich verwende HSQL, aber als Standalone. Per "normalen" Zugriff, also nicht Hibernate, funktioniert alles fehlerfrei.
 

HoaX

Top Contributor
sicher standalone und nicht embedded? beim embedded musst du nämlich die datenbank schön mit "shutdown" herunterfahren um nicht daten zu verlieren
 
G

Guest

Gast
Ja ich bin mit absolut sicher als Standalone, hier der Code der hibernate.cfg.xml:
Code:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:D:/tmp/firsthibernate</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
        <property name="hibernate.connection.shutdown">true</property>
        
        <property name="connection.pool_size">1</property>

        
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

        
        <property name="current_session_context_class">thread</property>

        
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        
        <property name="show_sql">true</property>

        
        <property name="hbm2ddl.auto">update</property>

        <mapping resource="de/laliluna/example/Honey.hbm.xml"/>

    </session-factory>

</hibernate-configuration>
 
J

Javalearner

Gast
Hier die Mapping-Datei der Honey-Klasse:

Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="de.laliluna.example">
  <class name="Honey" table="thoney" >
    <id name="id" column="id">
            <generator class="native"/>
    </id>
        <property name="name" type="string" column="name"></property>
    		<property name="taste" type="string" column="taste"></property>
  </class>

</hibernate-mapping>
 
G

Guest

Gast
Vorweg ich bin ein Hibernate Anfaenger. Aber sollte in der Mapping Datei nicht statt "type=string" type=java.lang.String stehen ?
 

HoaX

Top Contributor
Anonymous hat gesagt.:
J
<property name="connection.url">jdbc:hsqldb:D:/tmp/firsthibernate</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<property name="hibernate.connection.shutdown">true</property>

mpf ja, ich meinte natürlich servermode, und standalone und embedded sind das selbe. das hibernate.connection.shutdown hab ich so noch nie gesehn, aber ich weiß aus erfahrung dass auch der connectionurlparameter "shutdown=true" nicht tut was er soll.

erstell dir n shutdownhook der die datenbank sauber beendet oder lass die datenbank extern als server laufen, siehe http://hsqldb.sourceforge.net/doc/guide/ch01.html#N1013D
 
J

Javalearner

Gast
Danke Dir HoaX. Die Lösung lag tatsächlich in der Ausführung eines separaten Shutdowns:
Code:
package de.laliluna.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
* @author laliluna
*
*/
public class TestClient
{
  public static void main(String[] args)
  {
    createHoney();
//    Integer primaryKey = createHoney();
//    System.out.println("primary key is " + primaryKey);
//    updateHoney(primaryKey);
//    listHoney();
    System.out.println("Ende");
  }
  private static Integer createHoney() 
  { 
    Session session = null; 
    Transaction tx = null; 
    Logger log = Logger.getLogger("TestClient"); 
    log.info("creating honey"); 
    // [laliluna] our returned primary key 
    Integer id = null; 
    try 
    { 
      // [laliluna] get the session from the factory 
      session = HibernateSessionFactory.currentSession(); 
      // [laliluna] always start a transaction before doing something 
      // (even reading) from the database 
      tx = session.beginTransaction(); 
      tx.begin();
      // [laliluna] create a new object 
      Honey honey = new Honey(); 
      honey.setName("Sebastian's favourite honey"); 
      honey.setTaste("sweet"); 
      // [laliluna] save it to the database, Hibernate returns your object 
      // with the primary key field updated! 
      System.out.println("----Speichern beginnt!----"); 
      id = (Integer) session.save(honey); 
      System.out.println("----Speichern Ende!----"); 
      // [laliluna] commit your transaction or nothing is wrote to the db 
      System.out.println("----Commit beginnt!----"); 
      tx.commit();
      if(tx.wasCommitted())
      {
        System.out.println("Trans committed");
        
      }
      System.out.println("----Ende des Commits!----"); 
      System.out.println("----Schließen beginnt!----"); 
      // [laliluna] clean up (close the session) 
      session.flush();
      session.close(); 
      System.out.println("----Ende des Schließens!----"); 
      shutdown();
    } 
    catch (Throwable e) 
    { 
      log.error("Fehler", e);
      // [laliluna] when an error occured, try to rollback your 
      // transaction 
      if (tx != null) 
        try 
      { 
          tx.rollback(); 
      } 
      catch (HibernateException e1) 
      { 
        log.warn("rollback not successful", e1); 
      } 
      /* 
       * [laliluna] close your session after an exception!! Your session 
       * is in an undefined and unstable situation so throw it away! 
       * 
       */ 
      if (session != null) 
        try 
      { 
          session.close(); 
      } 
      catch (HibernateException e2) 
      { 
        log.warn("session close not successful", e2); 
      } 
    } 
    return id; 
  }

  private static void updateHoney(Integer primaryKey)
  {
    Session session = null;
    Transaction tx = null;
    Logger log = Logger.getLogger("TestClient");
    log.info("updating honey");
    try
    {
      // [laliluna] get the session from the factory
      session = HibernateSessionFactory.currentSession();
      // [laliluna] always start a transaction before doing something
      // (even reading) from the database
      tx = session.beginTransaction();
      // [laliluna] load object from the database
      Honey honey = (Honey) session.get(Honey.class, primaryKey);
      // [laliluna] honey is null when no object was found
      if (honey != null)
      {
        honey.setName("Sascha's favourite honey");
        honey.setTaste("very sweet");
      }
      session.flush();
      // [laliluna] commit your transaction or nothing is wrote to the db
      tx.commit();
      // [laliluna] clean up (close the session)
      session.close();
    } 
    catch (HibernateException e)
    {
      // [laliluna] when an error occured, try to rollback your
      // transaction
      if (tx != null)
        try
       {
          tx.rollback();
       }
      catch (HibernateException e1)
      {
        log.warn("rollback not successful");
      }
      /*
       * [laliluna] close your session after an exception!! Your session
       * is in an undefined and unstable situation so throw it away!
       *
       */
      if (session != null)
        try 
      {
          session.close();
      } 
      catch (HibernateException e2)
      {
        log.warn("session close not successful");
      }
    }
  }
  private static void listHoney()
  {
    Session session = null;
    Transaction tx = null;
    Logger log = Logger.getLogger("TestClient");
    log.info("listing honey");
    try 
    {
      // [laliluna] get the session from the factory
      session = HibernateSessionFactory.currentSession();
      // [laliluna] always start a transaction before doing something
      // (even reading) from the database
//      tx = session.beginTransaction();
////      List honeys = session.find("select from Honey");
//      for (Iterator iter = honeys.iterator(); iter.hasNext();) {
//      Honey honey = (Honey) iter.next();
//      System.out.println("Id " + honey.getId() + " Name "
//      + honey.getName());
//      }
      // [laliluna] commit your transaction or nothing is wrote to the db
      tx.commit();
      // [laliluna] clean up (close the session)
      session.close();
    } 
    catch (HibernateException e)
    {
      // [laliluna] when an error occured, try to rollback your
      // transaction
      if (tx != null)
        try
      {
          tx.rollback();
      } 
      catch (HibernateException e1)
      {
        log.warn("rollback not successful");
      }
      /*
       * [laliluna] close your session after an exception!! Your session
       * is in an undefined and unstable situation so throw it away!
       *
       */
      if (session != null)
        try
      {
          session.close();
      } 
      catch (HibernateException e2)
      {
        log.warn("session close not successful");
      }
    }
  }
  
  public static void shutdown() throws SQLException, ClassNotFoundException 
  {
    
    try
    {
    Connection conn;
    //  Den richtige Klasse für den HSQLDB-Treiber laden
    Class.forName("org.hsqldb.jdbcDriver");

    //Verbindung zur Datenbank herstellen und ggf. neue Datenbank erzeugen 
    conn = DriverManager.getConnection("jdbc:hsqldb:"
                                       + "D:/tmp/firsthibernate",    // Pfad incl. Dateiname
                                       "sa",                     // Benutzername
                                       "");
    Statement st = conn.createStatement();

    //Für einen "sauberen" Shutdown sorgen
    st.execute("SHUTDOWN");
    conn.close();
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }
  }
  
}
 
Status
Nicht offen für weitere Antworten.

Neue Themen


Oben