Hibernate mit MySql - Verständniss Frage

Status
Nicht offen für weitere Antworten.

bennyj

Mitglied
Hallo zusammen,

ich stehen in den Anfängen von Hibernate in Verbindung mit einer MySql Datenbank.
Ich hoffe ihr könnt mir etwas zu dem Problem sagen, ist glaube ich nur einen Verständniss frage.

Was ich bisher gemacht habe

ich habe mir eine einfaches Tutorial angeschaut

http://www.laliluna.de/first-hibernate-example-tutorial_de.html

und dies in Eclipse nachgebaut. Ich habe das Beispiel zum Laufen gebracht und die Daten werden in die DB geschrieben.



Soweit so gut, mein Problem fängt in der Ausführung an

Code:
	public static void main(String[] args) {
		
		Honey forestHoney = new Honey();
		forestHoney.setName("forest honey");
		forestHoney.setTaste("very sweet");
		
		Baum neuerBaum = new Baum();
		neuerBaum.setAst(5);
		neuerBaum.setName("Düsseldorf");
		
		Baum neuer2Baum = new Baum();
		neuer2Baum.setAst(4);
		neuer2Baum.setName("Rom");
		
		Honey countryHoney = new Honey();
		countryHoney.setName("country honey");
		countryHoney.setTaste("tasty");
		
		createHoney(forestHoney);
		createHoney(countryHoney);
		createBaum(neuerBaum);
		createBaum(neuer2Baum);
		// our instances have a primary key now:
		log.debug(forestHoney);
		log.debug(countryHoney);
		listHoney();
		deleteHoney(forestHoney);
		listHoney();

	}

Hierbei werden nun in 2 Tabellen 4 Objekte gespeichert und eins gelöscht. Wenn ich dies nochmal aussführe und die Atribute der beiden Klassen änder, finde ich nach dem Aussführen nur noch die neue Objekte in der DB wieder.

Was muß ich tun, damit ich einfach mehrere Objekte in der DB speicher und das belieg oft, so wie man es normalerweis nutzt?

Klingt vllt etwas komisch, aber ich finde nicht den Ansatz wo ich das bearbeiten kann.

Hoffe ich versteh das noch 🙂

Viele Grüße
BennyJ




Code:
/**
 * 
 * @author Sebastian Hennebrueder
 * created Feb 22, 2006
 * copyright 2006 by [url]http://www.laliluna.de[/url]
 */
package de.laliluna.hibernate;

import javax.naming.InitialContext;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;

/**
 * @author hennebrueder This class garanties that only one single SessionFactory
 *         is instanciated and that the configuration is done thread safe as
 *         singleton. Actually it only wraps the Hibernate SessionFactory.
 *         When a JNDI name is configured the session is bound to to JNDI,
 *         else it is only saved locally.
 *         You are free to use any kind of JTA or Thread transactionFactories.
 */
public class InitSessionFactory {

	/**
	 * Default constructor.
	 */
	private InitSessionFactory() {
	}

	/**
	 * Location of hibernate.cfg.xml file. NOTICE: Location should be on the
	 * classpath as Hibernate uses #resourceAsStream style lookup for its
	 * configuration file. That is place the config file in a Java package - the
	 * default location is the default Java package.

	 * 

	 * Examples: 

	 * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml". 
	 * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
	 */
	private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

	/** The single instance of hibernate configuration */
	private static final Configuration cfg = new Configuration();

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

	/**
	 * initialises the configuration if not yet done and returns the current
	 * instance
	 * 
	 * @return
	 */
	public static SessionFactory getInstance() {
		if (sessionFactory == null)
			initSessionFactory();
		return sessionFactory;
	}

	/**
	 * Returns the ThreadLocal Session instance. Lazy initialize the
	 * <code>SessionFactory</code> if needed.
	 * 
	 * @return Session
	 * @throws HibernateException
	 */
	public Session openSession() {
		return sessionFactory.getCurrentSession();
	}

	/**
	 * The behaviour of this method depends on the session context you have
	 * configured. 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
	 */
	public Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	/**
	 * initializes the sessionfactory in a safe way even if more than one thread
	 * tries to build a sessionFactory
	 */
	private static synchronized void initSessionFactory() {
		/*
		 * [laliluna] check again for null because sessionFactory may have been
		 * initialized between the last check and now
		 * 
		 */
		Logger log = Logger.getLogger(InitSessionFactory.class);
		if (sessionFactory == null) {
		

			try {
				cfg.configure(CONFIG_FILE_LOCATION);
				String sessionFactoryJndiName = cfg
				.getProperty(Environment.SESSION_FACTORY_NAME);
				if (sessionFactoryJndiName != null) {
					cfg.buildSessionFactory();
					log.debug("get a jndi session factory");
					sessionFactory = (SessionFactory) (new InitialContext())
							.lookup(sessionFactoryJndiName);
				} else{
					log.debug("classic factory");
					sessionFactory = cfg.buildSessionFactory();
				}

			} catch (Exception e) {
				System.err
						.println("%%%% Error Creating HibernateSessionFactory %%%%");
				e.printStackTrace();
				throw new HibernateException(
						"Could not initialize the Hibernate configuration");
			}
		}
	}
	
	public static void close(){
		if (sessionFactory != null)
			sessionFactory.close();
		sessionFactory = null;
	
	}
}

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.url">jdbc:mysql://server-inside.net/d0064f66</property>
    <property name="connection.username">d0064f66</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.password">JazND74EE</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">create</property>
    <mapping resource="de/laliluna/example/Baum.hbm.xml" />
    <mapping resource="de/laliluna/example/Honey.hbm.xml" />
  </session-factory>
</hibernate-configuration>

<?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="Baum" table="tbaum">
<id name="id">
<generator class="increment"></generator></id>
<property name="ast" type="integer"></property>
<property name="name" type="string"></property>
</class>
</hibernate-mapping
 
Hast du auch das öffnen und schließen der Transaction nicht vergessen?

Und äh:

jdbc:mysql://server-inside.net/d0064f66
d0064f66
JazND74EE

So und hier kannst du noch deine Bank, deine Kontonr und eine gültige Liste von Pins und Tans hinterlegen.
 
ja die tan und pins schicke ich per PM rüber ist glaub besser, dann kannst du die einzelnt benutzen bevor alle weg sind ;-)

aber nochmal zum problem, muß ich die session dannach schließen?

innerhalb der funktion

Code:
createBaum(neuer2Baum);

oder in einer hibernate XML datei?

Danke
 
In der Methode createBaum

muß die Transaktion geöffnet

Transaction tx = session.beginTransaction();

gespeichert

session.save();

und dannach die Transaction geschlossen

tx.commit();

Solltest du aber so haben, wenn du dich an das Tutorial gehalten hast.
Versuche doch am Ende der main-Methode die SessionFactory zu schließen.

InitSessionFactory.getInstance().close();
 
Hm ich habe das eingefügt.

und main 2x ausgeführt.

Code:
	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);

		log.debug(forestHoney);
		log.debug(countryHoney);
		listHoney();
		InitSessionFactory.getInstance().close();
	}

danach dann mit neue Paramertern


Code:
	public static void main(String[] args) {
		
		Honey forestHoney = new Honey();
		forestHoney.setName("new honey");
		forestHoney.setTaste("bigs weet");
		
		Honey countryHoney = new Honey();
		countryHoney.setName("World honey");
		countryHoney.setTaste("tasty");
		
		createHoney(forestHoney);
		createHoney(countryHoney);

		log.debug(forestHoney);
		log.debug(countryHoney);
		listHoney();
		InitSessionFactory.getInstance().close();
	}

wenn ich jetzt in die DB gucke sind in der tabelle nur 2 statt 4 einträge :-(

noch eine idee

Code:
20:27:41,182  INFO SessionFactoryImpl:769 - closing
20:27:41,182  INFO DriverManagerConnectionProvider:147 - cleaning up connection pool: jdbc:mysql://URL/DB
 
1. poste mal den gesamten log!

2. wie erstellst du die Tabellen für das Mapping per script oder über JAVA. Kann es vielleicht sein das du bei jeder Ausführung des Programms die Tabellen neu erstellst. Versuch mal die zeile 15 in der hibernate.cfg auszukommentieren.
Code:

Ich weiß zwar nicht genau was dieses Property macht, aber ich vermute, das es die Tabellen für die Datenbank jedesmal neu anlegt und deshalb, evtl. die Daten überschreibt.
 
😀 😀

Hey dank!!

Update irgendwie auch logisch ... das ich das nicht selbst drauf gekommen bin!!

VIELEN DANK :toll: :toll:
 
ja in deinem link stand auch :###

Bei create-drop verwirft Hibernate bei jedem Start alle vorhandenen Tabellen und legt diese neu an. Bei create versucht Hibernate die Tabellen neu anzulegen.

Also Danke das ich es gefunden habe
 
Status
Nicht offen für weitere Antworten.

Neue Themen


Zurück
Oben