# erste Schritte mit Hibernate



## pl4gu33 (16. Apr 2012)

Hey,... ich habe mich heute schon den halben Tag mit Hibernate beschäftigt und nach unzähligen Exception und Path Fehlern es nun einigermaßen zum Laufen bekommen, zumindest bis ich mein ersten Datensatz einfügen will.... 

(benutze XAMPP)

ich habe folgenden Code:


```
package first;


import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Entity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;




@Entity
@SequenceGenerator(name = "seq", sequenceName = "test_seq")
@Table(name="Team")
public class Team {
	@Id @Column(name="team_id")  @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq")
	private Long id;
	
	@Column(name="teamname",nullable=false)
	private String name;
	
	public Team(String name){
			name=this.name;
	}
	
	public static void main(String[] args){		
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		Session session=sessionFactory.openSession();
		session.save(new Team("test"));
		sessionFactory.close();
	}
}
```




```
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/mytest</property>
        <property name="connection.username">root</property>
        <property name="connection.password">hierstehtdaspw</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

       
        <!-- List the persistent classes here -->
        <mapping class="first.Team"/>       
        <!-- ... -->
  
        
    </session-factory>
</hibernate-configuration>
```


```
125 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
125 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.0.Final
141 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
141 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
141 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
203 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
203 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
313 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
375 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: first.Team
407 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity first.Team on table Team
453 [main] INFO org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring
469 [main] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
469 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
469 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 1
469 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
485 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:mysql://127.0.0.1:3306/mytest
485 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****}
782 [main] INFO org.hibernate.cfg.SettingsFactory - Database ->
       name : MySQL
    version : 5.5.16
      major : 5
      minor : 5
782 [main] INFO org.hibernate.cfg.SettingsFactory - Driver ->
       name : MySQL-AB JDBC Driver
    version : mysql-connector-java-5.1.19 ( Revision: [email]tonci.grgin@oracle.com[/email]-20111003110438-qfydx066wsbydkbw )
      major : 5
      minor : 1
797 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.Oracle9Dialect
813 [main] WARN org.hibernate.dialect.Oracle9Dialect - The Oracle9Dialect dialect has been deprecated; use either Oracle9iDialect or Oracle10gDialect instead
813 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
813 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
813 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
813 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
813 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
813 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
813 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
813 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): disabled
813 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
813 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
828 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
828 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
828 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
828 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
828 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
828 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
828 [main] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
860 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
938 [main] INFO org.hibernate.tuple.PojoInstantiator - no default (no-argument) constructor for class: first.Team (class must be instantiated by Interceptor)
1125 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
1188 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1109, SQLState: 42S02
1188 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Unknown table 'test_seq' in field list
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not get next sequence value
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
	at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:132)
	at org.hibernate.id.SequenceHiLoGenerator$1.getNextValue(SequenceHiLoGenerator.java:86)
	at org.hibernate.id.enhanced.OptimizerFactory$LegacyHiLoAlgorithmOptimizer.generate(OptimizerFactory.java:351)
	at org.hibernate.id.SequenceHiLoGenerator.generate(SequenceHiLoGenerator.java:83)
	at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
	at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
	at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
	at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
	at first.Team.main(Team.java:36)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'test_seq' in field list
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
	at java.lang.reflect.Constructor.newInstance(Unknown Source)
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
	at com.mysql.jdbc.Util.getInstance(Util.java:386)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4098)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4030)
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2677)
	at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2134)
	at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2300)
	at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:112)
	... 13 more
```


nun bekomm ich die Exception, ich würde da jetzt rauslesen, dass die Sequence nicht erstellt wird und er deshalb keine fortlaufende ID generiern kann aber ich verstehe nicht wieso ich habe auch schon versucht die Sequence manuell zu generieren aber gleicher Effekt ... oder ich stehe gerade auf dem Schlauch .... wäre nett wenn ihr mit nen paar Tipps dazu geben könnt


----------



## Marcinek (16. Apr 2012)

Die Tabelle existiert nicht?


```
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'test_seq' in field list
```


----------



## pl4gu33 (16. Apr 2012)

Marcinek hat gesagt.:


> Die Tabelle existiert nicht?
> 
> 
> ```
> ...



jap schon die DB ist komplett leer , aber soweit ich das verstanden habe, sollten die benötigten Tables ja automatisch erzeugt werden oder hab ich da was falsch verstanden ?

okay... ich hab gerade gefunden, dass ich dazu den Befehl :

property name="hibernate.hbm2ddl.auto">create</property>

bzw.

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

benutzen muss und das nicht automatisch passiert

nun bekomm ich zwar noch ne neue Exception aber die guck ich mir erstmal wieder selber an 

trotzdem danke


----------



## pl4gu33 (19. Apr 2012)

okay vll. kurz nochmal was wirklich falsch war, vll. hilft es ja irgendwem der das gleiche Problem hatte 

also erst einmal war weder das Create noch das Update Schuld für die Exception sondern, dass es in MySQL keine Sequencen gibt 

also statt:
@SequenceGenerator(name = "seq", sequenceName = "test_seq")
und 
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq")

einfach nur:
@GeneratedValue(strategy=GenerationType.AUTO)

als nächstes hatte ich das Problem, dass ich versucht hatte ein Objekt nur mit session.save(obj) zu speichern. Das wiederum hatte ich in einem Tutorial gesehen. Die Lösung für dieses Problem gabs hier :

http://www.dpunkt.de/leseproben/2663/Kapitel_6.pdf   auf Seite 2:

"Damit hat Hibernate den Termin aber noch nicht zwangsläufig in die
Datenbank geschrieben, und auf keinen Fall hat Hibernate die zugehörige
Datenbanktransaktion geschlossen.
Um Veränderungen an der Datenbank vorzunehmen, muss man
mit Transaktionen arbeiten. Dazu lässt man sich von der Session ein
Transaktionsobjekt geben und beendet die Transaktion am Ende mit
commit"


----------

