Hibernate und Oracle

Studdi23

Grünschnabel
Hallo,

ich arbeite mich momentan in Hibernate ein und versuche ein Tutorial zum Laufen zu bringen. Bei der Ausführung des Beispielprogramms erhalte ich folgende Exception:

PHP:
13:06:45,609  INFO Version:15 - Hibernate Annotations 3.4.0.GA
13:06:45,625  INFO Environment:543 - Hibernate 3.3.0.SP1
Exception in thread "main" java.lang.ExceptionInInitializerError
	at org.hibernate.cfg.Configuration.reset(Configuration.java:201)
	at org.hibernate.cfg.AnnotationConfiguration.reset(AnnotationConfiguration.java:233)
	at org.hibernate.cfg.Configuration.<init>(Configuration.java:220)
	at org.hibernate.cfg.Configuration.<init>(Configuration.java:224)
	at org.hibernate.cfg.AnnotationConfiguration.<init>(AnnotationConfiguration.java:108)
	at de.laliluna.hibernate.SessionFactoryUtil.<clinit>(SessionFactoryUtil.java:32)
	at de.laliluna.example.TestExample.createHoney(TestExample.java:92)
	at de.laliluna.example.TestExample.main(TestExample.java:28)
Caused by: java.lang.NullPointerException
	at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:167)
	at org.hibernate.cfg.Environment.<clinit>(Environment.java:558)
	... 8 more

Bin ein absoluter Anfänger auf diesem Gebiet und habe keine Ahnung was die Meldung bedeutet. Die .jar Bibliotheken welche sich in den Ordnern hibernate-annotations/ -distribution und -entitymanager befinden, wurden alle in die Classpath des Projekts mit aufgenommen. Als Datenbank verwende ich Oracle 10g XE. Die Tabelle "HONEY" mit den Spalten "ID","NAME","TASTE" sowie die Sequence "HONEY_SEQ" wurden bereits angelegt. Über Google find ich leider nur Hibernate-Tutorials in Verbindung mit MySQL oder PostgreSQL. Ich vermute das mit der DB-Konfiguration etwas nicht stimmt.
Nachfolgend alle Klassen und config-Dateien die sich im Eclipse-Projektordner befinden:

Honey.java

PHP:
package de.laliluna.example;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;

@Entity
public class Honey {

  @Id
  @GeneratedValue
	private Integer id;

	private String name;

	private String taste;

	public Honey() {

	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTaste() {
		return taste;
	}

	public void setTaste(String taste) {
		this.taste = taste;
	}

	@Override
	public String toString() {
		return "Honey: "+getId()+" Name: "+getName()+" Taste: "+getTaste();
	}
	
	
}

TestExample.java

PHP:
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.laliluna.hibernate.SessionFactoryUtil;

public class TestExample {

  final static Logger logger = LoggerFactory.getLogger(TestExample.class);

  /**
   * @param args
   */
  public static void main(String[] args) {
    Honey forestHoney = new Honey();
    forestHoney.setName("forest honey");
    forestHoney.setTaste("very sweet");
    Honey countryHoney = new Honey();
    countryHoney.setName("country honey");
    countryHoney.setTaste("tasty");
    createHoney(forestHoney);
    createHoney(countryHoney);
    // our instances have a primary key now:
    logger.debug("{}", forestHoney);
    logger.debug("{}", countryHoney);
    listHoney();
    deleteHoney(countryHoney);
    listHoney();
    forestHoney.setName("Norther Forest Honey");
    updateHoney(forestHoney);

  }

  private static void listHoney() {
    Transaction tx = null;
    Session session = SessionFactoryUtil.getInstance().getCurrentSession();
    try {
      tx = session.beginTransaction();
      List honeys = session.createQuery("select h from Honey as h")
              .list();
      for (Iterator iter = honeys.iterator(); iter.hasNext();) {
        Honey element = (Honey) iter.next();
        logger.debug("{}", element);
      }
      tx.commit();
    } catch (RuntimeException e) {
      if (tx != null && tx.isActive()) {
        try {
// Second try catch as the rollback could fail as well
          tx.rollback();
        } catch (HibernateException e1) {
          logger.debug("Error rolling back transaction");
        }
// throw again the first exception
        throw e;
      }


    }
  }

  private static void deleteHoney(Honey honey) {
    Transaction tx = null;
    Session session = SessionFactoryUtil.getInstance().getCurrentSession();
    try {
      tx = session.beginTransaction();
      session.delete(honey);
      tx.commit();
    } catch (RuntimeException e) {
      if (tx != null && tx.isActive()) {
        try {
// Second try catch as the rollback could fail as well
          tx.rollback();
        } catch (HibernateException e1) {
          logger.debug("Error rolling back transaction");
        }
// throw again the first exception
        throw e;
      }
    }
  }

  private static void createHoney(Honey honey) {
    Transaction tx = null;
    Session session = SessionFactoryUtil.getInstance().getCurrentSession();
    try {
      tx = session.beginTransaction();
      session.save(honey);
      tx.commit();
    } catch (RuntimeException e) {
      if (tx != null && tx.isActive()) {
        try {
// Second try catch as the rollback could fail as well
          tx.rollback();
        } catch (HibernateException e1) {
          logger.debug("Error rolling back transaction");
        }
// throw again the first exception
        throw e;
      }
    }
  }

   private static void updateHoney(Honey honey) {
    Transaction tx = null;
    Session session = SessionFactoryUtil.getInstance().getCurrentSession();
    try {
      tx = session.beginTransaction();
      session.update(honey);
      tx.commit();
    } catch (RuntimeException e) {
      if (tx != null && tx.isActive()) {
        try {
// Second try catch as the rollback could fail as well
          tx.rollback();
        } catch (HibernateException e1) {
          logger.debug("Error rolling back transaction");
        }
// throw again the first exception
        throw e;
      }
    }
  }
}

SessionFactoryUtil.java

PHP:
package de.laliluna.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class SessionFactoryUtil {

  /** The single instance of hibernate SessionFactory */
  private static org.hibernate.SessionFactory sessionFactory;

	/**
	 * disable contructor to guaranty a single instance
	 */
	private SessionFactoryUtil() {
	}

	static{
// Annotation and XML
    sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
// XML only
//    sessionFactory = new Configuration().configure().buildSessionFactory();
  }

	public static SessionFactory getInstance() {
		return sessionFactory;
	}

  /**
   * Opens a session and will not bind it to a session context
   * @return the session
   */
	public Session openSession() {
		return sessionFactory.openSession();
	}

	/**
   * Returns a session from the session context. If there is no session in the context it opens a session,
   * stores it in the context and returns it.
	 * This factory is intended to be used with a hibernate.cfg.xml
	 * including the following property <property
	 * name="current_session_context_class">thread</property> This would return
	 * the current open session or if this does not exist, will create a new
	 * session
	 * 
	 * @return the session
	 */
	public Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

  /**
   * closes the session factory
   */
	public static void close(){
		if (sessionFactory != null)
			sessionFactory.close();
		sessionFactory = null;
	
	}
}

Honey.hbm.xml

PHP:
<?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="HONEY">
        <id name="id" column="ID">
            <generator class="sequence">
                <param name="sequence">HONEY_SEQ</param>
            </generator>
	        <generator class="increment"/>
        </id>
        <property name="name" column="NAME"/>
        <property name="taste" column="TASTE"/>
    </class>
</hibernate-mapping>

hibernate.cfg.xml

PHP:
<?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">
<!-- Generated by MyEclipse Hibernate Tools.-->
<hibernate-configuration>
 <session-factory name="">
  <!--  OracleSQL connection -->
  <property name="connection.url">jdbc:oracle:thin:@XXX:1521:XE</property>
  <property name="connection.username">XXX</property>
  <property name="connection.password">XXX</property>
  <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
  <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
  <property name="current_session_context_class">thread</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <mapping resource="de/laliluna/example/Honey.hbm.xml" />
  <mapping class="de.laliluna.example.Honey"/>
 </session-factory>
</hibernate-configuration>
 
Zuletzt bearbeitet:

Neue Beiträge

Zurück