Hibernate 2.x mit Eclipse 2.1

  • Themenstarter Themenstarter Seb^
  • Beginndatum Beginndatum
Status
Nicht offen für weitere Antworten.
S

Seb^

Gast
Hi Leute,

kann mir irgendjemand sagen, wie ich Hibernate 2.x im WSAD 5.x/Eclipse 2.1 zum laufen krieg?
Ich hab schon die Dokus auf hibernate.org durchsucht sowie diverse Online-Artikel, aber es funktioniert mit keinem 🙁

MfG

Sebastian
 
Na ja, ich saug mir Hibernate2, dann erzeug ich das ganze mit ant.
Wenn ich dann die jar-files in den Build Path von meinem projekt einbinde krieg ich Fehler, dass jar-Archive nicht gefunden wurden.
Das nächste Problem ist, wie ich hibernate so konfiguriere, dass es eine verbindung mit meiner mysql datenbank herstellt. Bei tomcat muss man die server.xml editieren, aber wie funktioniert das ganze bei WSAD?
 
meinst du mit einer datasource? beim tocat musst du die server.xml nur dann editieren, wenn du mit einer solchen arbeiten willst

a) zu hibernate gehören ein ganzer haufen .jars! hast du alle nötigen dabei?

b) lies die doku für die hibernate.cfg.xml; du kannst auch ohne Datasource arbeiten...
 
ich hab mir das hibernate packet von sourceforge runtergeladen
welche .jar-s fehlen noch ?
also ant, log4j u.s.w. h ab ich schon
 
bei mir sinds folgende

ant.jar dom4j.jar jta.jar
apache.license.txt ehcache.jar jta.licence.txt
c3p0.jar hibernate-tools.jar junit.jar
c3p0.license.txt jaas.jar log4j.jar
cglib2.jar jaas.licence.txt odmg.jar
commons-collections.jar jboss-cache.jar optional.jar
commons-dbcp.jar jboss-common.jar oscache.jar
commons-lang.jar jboss-jmx.jar proxool.jar
commons-logging.jar jboss-system.jar README.txt
commons-pool.jar jcs.jar swarmcache.jar
concurrent.jar jdbc2_0-stdext.jar xalan.jar
connector.jar jdbc2_0-stdext.licence.txt xerces.jar
connector.licence.txt jgroups.jar xml-apis.jar


wie üblich kann man sich dann noch stundenlang durch die Doku wühlen, bis man weiss, für welchen Zweck man welche jar braucht; bei mir funktioniert folgende Teilmenge

c3p0.jar hibernate2.jar log4j.jar
cglib2.jar odmg.jar
commons-lang.jar jaas.jar optional.jar
commons-logging.jar jcs.jar oscache.jar
concurrent.jar jdbc2_0-stdext.jar
connector.jar jgroups.jar proxool.jar
dom4j.jar jta.jar swarmcache.jar
ehcache.jar
 
Ja, ok danke..die hab ich im Build Pfad drin.
Dann hab ich mir ne kleine Testanwendung geschrieben.
Hier die Sourcen

hibernate.cfg.xml
Code:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<hibernate-configuration package="de.hibernate">

    <session-factory>

        <property name="connection.datasource">java:com/mysql/jdbc/Driver</property>
        <property name="show_sql">false</property>
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>

        
        <mapping resource="Cat.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

Mapping-File (Cat.hbm.xml)

Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>

    <class name="net.sf.hibernate.examples.quickstart.Cat" table="CAT">

        <!-- A 32 hex character is our surrogate key. It's automatically
            generated by Hibernate with the UUID pattern. -->
        <id name="id" type="string" unsaved-value="null" >
            <column name="CAT_ID" sql-type="char(32)" not-null="true"/>
            <generator class="uuid.hex"/>
        </id>

        
        <property name="name">
            <column name="NAME" length="16" not-null="true"/>
        </property>

        <property name="sex"/>

        <property name="weight"/>

    </class>

</hibernate-mapping>

Cat.java

Code:
/*
 * Created on 29.11.2004
 *
 * To change the template for this generated file go to
 * Window&Preferences&Java&Code Generation&Code and Comments
 */
package de.hibernate;
import net.sf.hibernate.*;
/**
 * @author Sebastian
 *
 * To change the template for this generated type comment go to
 * Window&Preferences&Java&Code Generation&Code and Comments
 */


public class Cat {

	private String id;
	private String name;
	private char sex;
	private float weight;

	public Cat() {
	}

	public String getId() {
		return id;
	}

	private void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public char getSex() {
		return sex;
	}

	public void setSex(char sex) {
		this.sex = sex;
	}

	public float getWeight() {
		return weight;
	}

	public void setWeight(float weight) {
		this.weight = weight;
	}

}

Und schließlich noch mein Servlet, dass Hibernate einbinden sollte

Code:
package de.hibernate;

import java.io.IOException;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

/**
 * @version 	1.0
 * @author
 */
public class Test extends HttpServlet {
	private static SessionFactory sessionFactory;
	public static final ThreadLocal session = new ThreadLocal();
	
	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		//	static {
				try {
					// Create the SessionFactory
					sessionFactory = new Configuration().configure().buildSessionFactory();
				} catch (Throwable ex) {
					throw new ExceptionInInitializerError(ex);
				}
		//	}

	}

	

	public static Session currentSession() throws HibernateException {
		Session s = (Session) session.get();
		// Open a new Session, if this Thread has none yet
		if (s == null) {
			s = sessionFactory.openSession();
			session.set(s);
		}
		return s;
	}

	public static void closeSession() throws HibernateException {
		Session s = (Session) session.get();
		session.set(null);
		if (s != null)
			s.close();
	}	
	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {

	}

}

So, die Klassen u.s.w. sind wie gesagt nur als Test gedacht. Eclipse meldet mir, dass zum Host "hibernate..." keine Verbindung hergestellt werden kann. Wenn ich das ganze Complier krieg ich folgende Fehlermeldung:

29.11.04 17:41:07:464 CET] 54b3598a Configuration I net.sf.hibernate.cfg.Configuration configuring from resource: /hibernate.cfg.xml
[29.11.04 17:41:07:464 CET] 54b3598a Configuration I net.sf.hibernate.cfg.Configuration Configuration resource: /hibernate.cfg.xml
[29.11.04 17:41:07:624 CET] 54b3598a XMLHelper E net.sf.hibernate.util.XMLHelper Error parsing XML: /hibernate.cfg.xml(5) Das Attribut "package" muss für Elementtyp "hibernate-configuration" deklariert werden.
[29.11.04 17:41:07:854 CET] 54b3598a Configuration E net.sf.hibernate.cfg.Configuration problem parsing configuration/hibernate.cfg.xml
[29.11.04 17:41:07:864 CET] 54b3598a Configuration E net.sf.hibernate.cfg.Configuration TRAS0014I: Die folgende Ausnahmebedingung wurde protokolliert: net.sf.hibernate.MappingException: invalid configuration
at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:959)
at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:902)
at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:888)
at de.hibernate.Test.doGet(Test.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:1020)
at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:561)
at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:198)
at com.ibm.ws.webcontainer.srt.WebAppInvoker.doForward(WebAppInvoker.java:80)
at com.ibm.ws.webcontainer.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:212)
at com.ibm.ws.webcontainer.cache.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:71)
at com.ibm.ws.webcontainer.cache.invocation.CacheableInvocationContext.invoke(CacheableInvocationContext.java:116)
at com.ibm.ws.webcontainer.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:186)
at com.ibm.ws.webcontainer.oselistener.OSEListenerDispatcher.service(OSEListener.java:334)
at com.ibm.ws.webcontainer.http.HttpConnection.handleRequest(HttpConnection.java:56)
at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:618)
at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:439)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:593)
Caused by: org.xml.sax.SAXParseException: Das Attribut "package" muss für Elementtyp "hibernate-configuration" deklariert werden.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:232)
at org.apache.xerces.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:173)
at org.apache.xerces.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:362)
at org.apache.xerces.impl.XMLErrorReporter.reportError(XMLErrorReporter.java(Inlined Compiled Code))
at org.apache.xerces.impl.dtd.XMLDTDValidator.addDTDDefaultAttrsAndValidate(XMLDTDValidator.java(Compiled Code))
at org.apache.xerces.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java(Compiled Code))
at org.apache.xerces.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java(Compiled Code))
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java(Compiled Code))
at org.apache.xerces.impl.XMLDocumentScannerImpl$ContentDispatcher.scanRootElementHook(XMLDocumentScannerImpl.java:950)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(XMLDocumentFragmentScannerImpl.java(Compiled Code))
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:333)
at org.apache.xerces.parsers.StandardParserConfiguration.parse(StandardParserConfiguration.java:525)
at org.apache.xerces.parsers.StandardParserConfiguration.parse(StandardParserConfiguration.java:581)
at org.apache.xerces.parsers.XMLParser.parse(XMLParser.java:147)
at org.apache.xerces.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1158)
at org.dom4j.io.SAXReader.read(SAXReader.java:339)
at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:958)
... 25 more
.
net.sf.hibernate.MappingException: invalid configuration
at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:959)

Den Rest der Fehlermeldung hab ich mal weggelassen 🙂

Ich hab in der Cat.hbm.xml in dem <hibernate-mapping> auch schon ne package angabe versucht, da bringt er mir dann, dass das package-Attribut beim Attribut hibernate-configuration stehen sollte.

Schonmal danke für die Hilfe

MfG

Sebastian
 
Error parsing XML: /hibernate.cfg.xml(5) Das Attribut "package" muss für Elementtyp "hibernate-configuration" deklariert werden.


-> das heisst ja wohl, dass das Attribut nicht in der DTD ist und du es weglassen sollst!

woher hast du das eigentlich, das Standard Cats Example aus der Doku hat ja nix dergleichen
 
Ich hab das Package-Attribut schon weggelassen, dann meckert er genauso 🙁

Das ist das Cats Example, nur n bissl abgeändert.
 
mit abgeändert meine ich folgendes:

sql-dialect auf MySql geändert
die methoden der HibernateUtil Klasse in meine Test-Klasse eingebaut

Könntest du mir ungefähr beschreiben, welche jar-s ich wo reinkopieren muss, welche jars ich zum build path hinzufügen muss, wie ich die cfgs schreiben muss?
ich hab echt schon ewig dei doku studiert, bringt mich aber null weiter
 
wie ist denn die situation?

hibernate.cfg.xml kann/soll direkt in WEB-INF/classes liegen, du brauchst nix sonst zu konfigurieren

die Cat.hbm.xml soll direkt neben Cat.class liegen (also in WEB-INF/de/hibernate/

(komisches privates package übrigens)

welche Fehlermeldung? wann?

deine Klasse liegt im package de.hibernate, in der cfg Datei schreibst du aber

net.sf.hibernate.examples.quickstart.Cat

was ist richtig?
 
ok danke sc´honmal ich änder das ab und meld mich nochmal!
was meinst du mir "privates package" ?
 
wenn du de.hibernate für eigene Sachen nimmst, würde ja man meinen, dass du mit "hibernate" was zu tun hast

lieber de.vorname.nachname.test oder so

ist aber eine reine Geschmacksfrage, nicht wirklich wichtig 🙂
 
So, ich hab noch n Beispiel gefunde und ein bisschen abgeändert. Sieht folgendermasen aus

Package: hb

Main.java

Code:
/*
 * Created on 04.12.2004
 *
 * To change the template for this generated file go to
 * Window&Preferences&Java&Code Generation&Code and Comments
 */
package hb;

/**
 * @author Sebastian
 *
 * To change the template for this generated type comment go to
 * Window&Preferences&Java&Code Generation&Code and Comments
 */
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import hb.*;

public class Main {    
	public static void main ( String[] args )
		throws MappingException,
			   HibernateException
	{
		Configuration cfg = new Configuration();
		cfg.addClass( hb.Keyword.class );        
		SessionFactory sessions = cfg.buildSessionFactory();
		Session session = sessions.openSession();        
		Transaction tx = null;
		Keyword     kw = new Keyword( 1,"red" );
		try {
			tx = session.beginTransaction();
			session.save( kw );
	//		tx.commit();
		}
		catch ( HibernateException he ) {
			if ( tx != null ) tx.rollback();
			throw he;
			
		}
		finally {
			session.close();
		}
		
	}
}

hibernate.properties

Code:
#
#
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost/hibernate
hibernate.connection.username=root
hibernate.connection.password=test
hibernate.connection.pool_size=2
#
hibernate.dialect=net.sf.hibernate.dialect.MySqlDialect
#
# $Id: hibernate.properties,v 1.1 2003/07/05 21:39:57 dwight Exp $
#

Keyword.hbm.xml

Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
  <class name="hb.Keyword" 
         table="keywords">    
         <id name="id" 
        type="integer"
        column="id">
        <generator class="native" />
  </id>    
  <property name="name" 
              column="NAME" 
              not-null="true"
              unique="false"
              />
  </class>
</hibernate-mapping>

Keyword.java

Code:
/*
 * Created on 04.12.2004
 *
 * To change the template for this generated file go to
 * Window&Preferences&Java&Code Generation&Code and Comments
 */
package hb;

/**
 * @author Sebastian
 *
 * To change the template for this generated type comment go to
 * Window&Preferences&Java&Code Generation&Code and Comments
 */
public class Keyword {
	private int id;
	private String name;
	public Keyword(){}
	public Keyword( int id, String name){
		this.id = id;
		this.name = name;
	}
	public void setId(int id){
		this.id = id;
	}
	public void setName(String name){
		this.name = name;
	}
	public int getId(){
		return id;
	}
	public String getName(){
		return name;
	}
}

Ich benutz MySql 4.x, meine Datenbank heißt "hibernate", die Tabelle heist "keywords" und hat die Felder id (integer, primärschlüssel und die restlichen attribute die in dem mapping file steheen) und name ( varchar u.s.w.).

Wenn ich das ganze ausführe krieg ich die Meldung "Couldn't find Table hibernate.hibernate_unique_key", dann hab ich die Tabelle hibernate_unique_key erstellt mit den feldern "next_hi" (integer) dann bring er mir die meldung "You have to populate the table"

Compiler-Log (mit hibernate_unique_key Tabelle):

log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
net.sf.hibernate.id.IdentifierGenerationException: could not read a hi value - you need to populate the table: hibernate_unique_key
at net.sf.hibernate.id.TableGenerator.generate(TableGenerator.java:98)
at net.sf.hibernate.id.TableHiLoGenerator.generate(TableHiLoGenerator.java:59)
at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:774)
at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:747)
at hb.Main.main(Main.java:32)
Exception in thread "main"

Compiler-Log (ohne hibernate_unique_key Tabelle):

log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
net.sf.hibernate.exception.GenericJDBCException: Could not save object
at net.sf.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:81)
at net.sf.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:70)
at net.sf.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:30)
at net.sf.hibernate.impl.SessionImpl.convert(SessionImpl.java:4110)
at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:792)
at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:747)
at hb.Main.main(Main.java:32)
Caused by: java.sql.SQLException: General error message from server: "Table 'hibernate.hibernate_unique_key' doesn't exist"
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1997)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1167)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1278)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2251)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1586)
at net.sf.hibernate.id.TableGenerator.generate(TableGenerator.java:94)
at net.sf.hibernate.id.TableHiLoGenerator.generate(TableHiLoGenerator.java:59)
at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:774)
... 2 more
Exception in thread "main"

Die nötigen JAR-Archive sind im Build-Path des Projektes. Wenn ich das Objekt nicht in der Datenbank speichern will funktioniert alles, deshalb glaub ich mal dass es nicht an dem MySql-connector oder an der Datenbankverbindung liegt.

Vielen Dank schonmal für die Hilfe!
 
Oleole, ich habs zumlaufen bekommen! Ich hab meine hibernate.properties abgeändert!

hibernate.connection.username=<das wüsstet ihr gerne>
hibernate.connection.password=<und das hier erst😀>
hibernate.connection.url=jdbc:mysql://localhost/hibernate
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect
 
Status
Nicht offen für weitere Antworten.

Zurück
Oben