Unerklärliche Hibernate Exception

mavinatic

Bekanntes Mitglied
Hey ihr Winterschlafenden ;)

Ich bekomme eine für mich unerklärliche Exception:

Java:
19:59:24,896  INFO Environment:456 - Hibernate 3.0rc1
19:59:24,912  INFO Environment:469 - hibernate.properties not found
19:59:24,912  INFO Environment:502 - using CGLIB reflection optimizer
19:59:24,912  INFO Environment:532 - using JDK 1.4 java.sql.Timestamp handling
19:59:24,912  INFO Configuration:1228 - configuring from resource: /hibernate.cfg.xml
19:59:24,912  INFO Configuration:1199 - Configuration resource: /hibernate.cfg.xml
19:59:25,224  INFO Configuration:439 - Mapping resource: account.hbm.xml
19:59:25,412  INFO HbmBinder:256 - Mapping class: de.Webshop.AccountManager.DataObjects.Account -> accounts
19:59:25,443  INFO Configuration:1340 - Configured SessionFactory: null
19:59:25,443  INFO Configuration:844 - processing extends queue
19:59:25,443  INFO Configuration:848 - processing collection mappings
19:59:25,443  INFO Configuration:857 - processing association property references
19:59:25,443  INFO Configuration:884 - processing foreign key constraints
19:59:25,521  INFO Dialect:89 - Using dialect: org.hibernate.dialect.MySQLDialect
19:59:25,521  INFO SettingsFactory:87 - Maximum outer join fetch depth: 2
19:59:25,521  INFO SettingsFactory:90 - Default batch fetch size: 1
19:59:25,521  INFO SettingsFactory:94 - Generate SQL with comments: disabled
19:59:25,521  INFO SettingsFactory:98 - Order SQL updates by primary key: disabled
19:59:25,521  INFO SettingsFactory:273 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
19:59:25,537  INFO ASTQueryTranslatorFactory:21 - Using ASTQueryTranslatorFactory
19:59:25,537  INFO SettingsFactory:106 - Query language substitutions: {}
19:59:25,537  INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
19:59:25,537  INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 10
19:59:25,537  INFO DriverManagerConnectionProvider:45 - autocommit mode: true
19:59:25,552  INFO DriverManagerConnectionProvider:80 - using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/webshop
19:59:25,552  INFO DriverManagerConnectionProvider:86 - connection properties: {user=customers, password=****, autocommit=true}
19:59:25,802  INFO SettingsFactory:148 - JDBC batch size: 15
19:59:25,802  INFO SettingsFactory:151 - JDBC batch updates for versioned data: disabled
19:59:25,818  INFO SettingsFactory:156 - Scrollable result sets: enabled
19:59:25,818  INFO SettingsFactory:164 - JDBC3 getGeneratedKeys(): enabled
19:59:25,818  INFO TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
19:59:25,818  INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
19:59:25,818  INFO SettingsFactory:176 - Automatic flush during beforeCompletion(): disabled
19:59:25,818  INFO SettingsFactory:179 - Automatic session close at end of transaction: disabled
19:59:25,818  INFO SettingsFactory:260 - Cache provider: org.hibernate.cache.EhCacheProvider
19:59:25,833  INFO SettingsFactory:187 - Second-level cache: enabled
19:59:25,833  INFO SettingsFactory:192 - Optimize cache for minimal puts: disabled
19:59:25,833  INFO SettingsFactory:199 - Structured second-level cache entries: enabled
19:59:25,833  INFO SettingsFactory:203 - Query cache: disabled
19:59:25,833  INFO SettingsFactory:210 - Echoing all SQL to stdout
19:59:25,833  INFO SettingsFactory:214 - Statistics: disabled
19:59:25,833  INFO SettingsFactory:218 - Deleted entity synthetic identifier rollback: disabled
19:59:25,833  INFO SettingsFactory:232 - Default entity-mode: pojo
19:59:25,974  INFO SessionFactoryImpl:140 - building session factory
19:59:25,974 DEBUG CacheManager:191 - Creating new CacheManager with default config
19:59:25,974 DEBUG CacheManager:164 - Configuring ehcache from classpath.
19:59:25,974  WARN Configurator:126 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Dokumente%20und%20Einstellungen/Administrator/Desktop/Projekte/Hibernate%20Test/libs/ehcache-1.1.jar!/ehcache-failsafe.xml
19:59:25,990 DEBUG Configuration$DiskStore:185 - Disk Store Path: C:\DOKUME~1\ADMINI~1\LOKALE~1\Temp\
19:59:26,240  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
19:59:26,240  INFO Dialect:89 - Using dialect: org.hibernate.dialect.MySQLDialect
19:59:26,240  INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
19:59:26,240  INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 10
19:59:26,240  INFO DriverManagerConnectionProvider:45 - autocommit mode: true
19:59:26,255  INFO DriverManagerConnectionProvider:80 - using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/webshop
19:59:26,255  INFO DriverManagerConnectionProvider:86 - connection properties: {user=customers, password=****, autocommit=true}
19:59:26,255  INFO SchemaUpdate:105 - Running hbm2ddl schema update
19:59:26,255  INFO SchemaUpdate:117 - fetching database metadata
19:59:26,287  INFO SchemaUpdate:133 - updating schema
19:59:26,287  INFO Configuration:844 - processing extends queue
19:59:26,287  INFO Configuration:848 - processing collection mappings
19:59:26,287  INFO Configuration:857 - processing association property references
19:59:26,287  INFO Configuration:884 - processing foreign key constraints
19:59:26,333  INFO TableMetadata:38 - table found: webshop.accounts
19:59:26,333  INFO TableMetadata:39 - columns: [id, username, email, password]
19:59:26,333  INFO TableMetadata:40 - foreign keys: []
19:59:26,333  INFO TableMetadata:41 - indexes: [primary]
19:59:26,333  INFO SchemaUpdate:153 - schema update complete
19:59:26,333  INFO DriverManagerConnectionProvider:147 - cleaning up connection pool: jdbc:mysql://localhost:3306/webshop
19:59:26,333  INFO SessionFactoryImpl:366 - Checking 0 named queries
19:59:26,396 DEBUG SQL:292 - SELECT * FROM accounts
Hibernate: SELECT * FROM accounts
19:59:26,412  WARN JDBCExceptionReporter:57 - SQL Error: 0, SQLState: S0022
19:59:26,412 ERROR JDBCExceptionReporter:58 - Column 'ID0_' not found.
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not execute query
    at org.hibernate.exception.ErrorCodeConverter.handledNonSpecificException(ErrorCodeConverter.java:92)
    at org.hibernate.exception.ErrorCodeConverter.convert(ErrorCodeConverter.java:80)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.loader.Loader.doList(Loader.java:1502)
    at org.hibernate.loader.Loader.list(Loader.java:1482)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:103)
    at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1333)
    at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:146)
    at de.Webshop.AccountManager.Hibernate.HConnection.getAllAccounts(HConnection.java:32)
    at de.Webshop.AccountManager.Startup.Main.main(Main.java:27)
Caused by: java.sql.SQLException: Column 'ID0_' not found.
    at com.mysql.jdbc.ResultSet.findColumn(ResultSet.java:2316)
    at com.mysql.jdbc.ResultSet.getInt(ResultSet.java:1287)
    at org.hibernate.type.IntegerType.get(IntegerType.java:26)
    at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:77)
    at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:68)
    at org.hibernate.loader.Loader.getKeyFromResultSet(Loader.java:650)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:277)
    at org.hibernate.loader.Loader.doQuery(Loader.java:384)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:203)
    at org.hibernate.loader.Loader.doList(Loader.java:1499)
    ... 6 more

Das hier ist die Hibernate.cfg.xml

Java:
<?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="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
        <property name="hibernate.connection.password">customers</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/webshop</property>
        <property name="hibernate.connection.username">customers</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLMyISAMDialect</property>
        <property name="hibernate.connection.pool_size">10</property>
          <property name="show_sql">true</property>
          <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
          <property name="connection.autocommit">true</property>
          <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="account.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

account.hbm.xml
Java:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="de.Webshop.AccountManager.DataObjects.Account" table="accounts">
   <id name="id" type="integer" column="ID" >
   <generator class="assigned"/>
  </id>

  <property name="username">
     <column name="USERNAME" />
  </property>
  <property name="password">
    <column name="PASSWORD"/>
  </property>
  <property name="email">
    <column name="EMAIL"/>
  </property>
 </class>
</hibernate-mapping>

MainClass:

Java:
package de.Webshop.AccountManager.Startup;
import java.util.List;

import org.hibernate.Session;

import de.Webshop.AccountManager.DataObjects.Account;
import de.Webshop.AccountManager.Hibernate.HConnection;


public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HConnection connection = new HConnection();
        Session session = connection.createConnection();
//        Account account = new Account();
//        account.setId(1000);
//        account.setEmail("test@test-mail.com");
//        account.setUsername("test");
//        account.setPassword("test");
//        
//        connection.saveAccount(session, account);
        
        List<Account> list = connection.getAllAccounts(session);
        for(int i=0;i<list.size();i++) {
            System.out.println(list.get(i).getUsername());
        }
    }

}

HConnection-Class
Java:
package de.Webshop.AccountManager.Hibernate;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import de.Webshop.AccountManager.DataObjects.Account;

public class HConnection {
    public Session createConnection() {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        
        return session;
    }
    
    public void saveAccount(Session session, Account object) {
        Transaction tx = session.beginTransaction();
        session.save(object);
        tx.commit();
    }
    public void closeConnection(Session session) {
        session.flush();
        session.close();
    }
    public List<Account> getAllAccounts(Session session) {
        Transaction tx = session.beginTransaction();
        List<Account> accounts = session.createSQLQuery("SELECT * FROM accounts").addEntity("Account", Account.class).list();
        return accounts;
    }
}

Und noch die JavaBean: ACCOUNT
Java:
package de.Webshop.AccountManager.DataObjects;

public class Account {
    private String username;
    private String password;
    private String email;
    private long id;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
}

Ich hab nun alle meine Klassen gepostet, wie ihr seht habe ich keine Column "ID_0" ich versteh nicht warum ich dann die Exception dafür bekomme, denn meine TABLE Column ID nennt sich "ID" wofür ist diese ID_0? ich verstehs nicht.

Gruß George
 
M

Marcinek

Gast
Steht drin:

Column 'ID0_' not found.


Für mich wäre das nicht "unerklärlich"

Ich schätze mal, dass das passiert, wenn man select * from macht.

Dann möchte er eine ID, er bennt sie um in id0, haben.
 
Zuletzt bearbeitet von einem Moderator:
M

Marcinek

Gast
Probiere es aus.

Und an der session gibt es 2 createQuery(). Das eine erzeugt SQL und das andere HQL.

Du müsstest das HQL verwenden.
 

KSG9|sebastian

Top Contributor
Zuerst verwende die Methode createQuery - die nimmt HQL statt SQL. Damit brauchst du auch kein addEntity mehr.

Existiert die Tabelle schon? Sicher das "id" kein reserviertes Schlüsselwort der Datenbank ist. Solche Dinge hatte ich auch schon.
 

mavinatic

Bekanntes Mitglied
Hallo ihrs,
ich bekomme nun eine weitere exception?! Zu dem habe ich meine Table von der mysql datenbank auf account umbenannt nicht das ihr euch wundert?!. Ich hab das doch alles in der hibernate.cfg.xml eingetragen :O?! Warum gehts nicht?

Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxError: account is not mapped.
 

MySelV

Aktives Mitglied
Hi,

Dann teile Hibernate auch mit, dass du die Tabelle umbenannt hast:

Java:
@Table(name = "account")
public class Account {

}

Wobei das eigentlich der Standardname für die Tabelle wäre. Ich weiß nicht wie clever Hibernate.ddl bei "update" ist. Mach mal ein drop-create zum Test.

Edit: Poste nochmal deine hibernate.cfg.xml und auch dein Query, wie es jetzt aussieht. Diese AST Fehler hatte ich auch schon oft, obwohl nur die Syntax der Query falsch war.
 

mavinatic

Bekanntes Mitglied
<?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="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.password">customers</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/webshop</property>
<property name="hibernate.connection.username">customers</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLMyISAMDialect</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.autocommit">true</property>
<mapping resource="account.hbm.xml"/>
</session-factory>
</hibernate-configuration>


Meine neue Exception (=org.hibernate.hql.ast.QuerySyntaxError: account is not mapped. [SELECT acc.ID,acc.USERNAME,acc.PASSWORD,acc.EMAIL FROM account AS acc])
 
Zuletzt bearbeitet:

MySelV

Aktives Mitglied
Hi,

der Fehler liegt bei

"FROM account AS acc".

Hibernate arbeitet immer mit den Objekten! Das heißt du musst bei allen Zugriffen auf Tabellen den Klassennamen verwenden. Ergo: Account und nicht account!


Grüße
 

mavinatic

Bekanntes Mitglied
Gut das hat geklappt aber ich verzweifel solangsam denn ich hab die nächste exception ;O

Java:
Exception in thread "main" org.hibernate.QueryException: could not resolve property: ID of: de.Webshop.AccountManager.DataObjects.Account [SELECT acc.ID,acc.USERNAME,acc.PASSWORD,acc.EMAIL FROM de.Webshop.AccountManager.DataObjects.Account AS acc]
 

MySelV

Aktives Mitglied
Morgen,

die Felder / Attribute werden auch über das Objekt angesprochen und müssen deshalb genauso wie im Objekt sein. Groß- Kleinschreibung ist bei Java doch schon immer wichtig...
So sollte es gehen: acc.id, ...

Grüße
 

mavinatic

Bekanntes Mitglied
Was würde ich Ohne DICH machen? Danke Vielmals für die Hilfe! aber wieder ne exception wo ich nicht weiterweiß wenn ich das alles bei google eingebe bekomme ich keine ergebnisse :(

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to de.Webshop.AccountManager.DataObjects.Account
at de.Webshop.AccountManager.Startup.Main.main(Main.java:29)

Es kann nicht nach ACCOUNT gecastet werden Oo warum? und wo caste Ich? Wahrscheinlich von DB zu Object?!
 

MySelV

Aktives Mitglied
Hi,

jemanden anderen fragen, würdest du ohne mich ;)

Kompletter Stacktrace wäre gut, aber spontan tippe ich auch die Methode getAllAccounts()

Grüße

Edit: Am besten du debugst die Methode mal. Und es wäre gut, wenn du die Transaktion auch wieder schließt, nachdem du die Accounts abgefragt hast.
 
Zuletzt bearbeitet:

mavinatic

Bekanntes Mitglied
Die Klasse HConnection

Java:
package de.Webshop.AccountManager.Hibernate;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import de.Webshop.AccountManager.DataObjects.Account;

public class HConnection {
    public Session createConnection() {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        
        return session;
    }
    
    public void saveAccount(Session session, Account object) {
        Transaction tx = session.beginTransaction();
        session.save(object);
        tx.commit();
    }
    public void closeConnection(Session session) {
        session.flush();
        session.close();
    }
    public List<Account> getAllAccounts(Session session) {
        Transaction tx = session.beginTransaction();
        List<Account> accounts = session.createQuery("SELECT acc.id,acc.username,acc.password,acc.email FROM Account AS acc").list();
        tx.commit();
        return accounts;
    }
}

Kompletter Stracktrace...
Java:
11:21:38,828  INFO Environment:456 - Hibernate 3.0rc1
11:21:38,828  INFO Environment:469 - hibernate.properties not found
11:21:38,844  INFO Environment:502 - using CGLIB reflection optimizer
11:21:38,844  INFO Environment:532 - using JDK 1.4 java.sql.Timestamp handling
11:21:38,844  INFO Configuration:1228 - configuring from resource: /hibernate.cfg.xml
11:21:38,844  INFO Configuration:1199 - Configuration resource: /hibernate.cfg.xml
11:21:39,125  INFO Configuration:439 - Mapping resource: account.hbm.xml
11:21:39,219  INFO HbmBinder:256 - Mapping class: de.Webshop.AccountManager.DataObjects.Account -> account
11:21:39,266  INFO Configuration:1340 - Configured SessionFactory: null
11:21:39,266  INFO Configuration:844 - processing extends queue
11:21:39,266  INFO Configuration:848 - processing collection mappings
11:21:39,266  INFO Configuration:857 - processing association property references
11:21:39,266  INFO Configuration:884 - processing foreign key constraints
11:21:39,391  INFO Dialect:89 - Using dialect: org.hibernate.dialect.MySQLDialect
11:21:39,407  INFO SettingsFactory:87 - Maximum outer join fetch depth: 2
11:21:39,407  INFO SettingsFactory:90 - Default batch fetch size: 1
11:21:39,407  INFO SettingsFactory:94 - Generate SQL with comments: disabled
11:21:39,407  INFO SettingsFactory:98 - Order SQL updates by primary key: disabled
11:21:39,407  INFO SettingsFactory:273 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
11:21:39,485  INFO ASTQueryTranslatorFactory:21 - Using ASTQueryTranslatorFactory
11:21:39,500  INFO SettingsFactory:106 - Query language substitutions: {}
11:21:39,516  INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
11:21:39,516  INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 10
11:21:39,516  INFO DriverManagerConnectionProvider:45 - autocommit mode: true
11:21:39,547  INFO DriverManagerConnectionProvider:80 - using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/webshop
11:21:39,547  INFO DriverManagerConnectionProvider:86 - connection properties: {user=customers, password=****, autocommit=true}
11:21:39,797  INFO SettingsFactory:148 - JDBC batch size: 15
11:21:39,797  INFO SettingsFactory:151 - JDBC batch updates for versioned data: disabled
11:21:39,797  INFO SettingsFactory:156 - Scrollable result sets: enabled
11:21:39,797  INFO SettingsFactory:164 - JDBC3 getGeneratedKeys(): enabled
11:21:39,797  INFO TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
11:21:39,828  INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
11:21:39,828  INFO SettingsFactory:176 - Automatic flush during beforeCompletion(): disabled
11:21:39,828  INFO SettingsFactory:179 - Automatic session close at end of transaction: disabled
11:21:39,828  INFO SettingsFactory:260 - Cache provider: org.hibernate.cache.EhCacheProvider
11:21:39,828  INFO SettingsFactory:187 - Second-level cache: enabled
11:21:39,828  INFO SettingsFactory:192 - Optimize cache for minimal puts: disabled
11:21:39,828  INFO SettingsFactory:199 - Structured second-level cache entries: enabled
11:21:39,828  INFO SettingsFactory:203 - Query cache: disabled
11:21:39,828  INFO SettingsFactory:210 - Echoing all SQL to stdout
11:21:39,828  INFO SettingsFactory:214 - Statistics: disabled
11:21:39,828  INFO SettingsFactory:218 - Deleted entity synthetic identifier rollback: disabled
11:21:39,828  INFO SettingsFactory:232 - Default entity-mode: pojo
11:21:40,063  INFO SessionFactoryImpl:140 - building session factory
11:21:40,078 DEBUG CacheManager:191 - Creating new CacheManager with default config
11:21:40,078 DEBUG CacheManager:164 - Configuring ehcache from classpath.
11:21:40,094  WARN Configurator:126 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Dokumente%20und%20Einstellungen/Administrator/Desktop/Projekte/Hibernate%20Test/libs/ehcache-1.1.jar!/ehcache-failsafe.xml
11:21:40,094 DEBUG Configuration$DiskStore:185 - Disk Store Path: C:\DOKUME~1\ADMINI~1\LOKALE~1\Temp\
11:21:40,453  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
11:21:40,453  INFO SessionFactoryImpl:366 - Checking 0 named queries
11:21:40,610 DEBUG parser:83 - throwQueryException() : no errors
11:21:40,672 DEBUG parser:83 - throwQueryException() : no errors
11:21:40,688 DEBUG parser:83 - throwQueryException() : no errors
11:21:40,703 DEBUG SQL:292 - select account0_.ID as col_0_0_, account0_.USERNAME as col_1_0_, account0_.PASSWORD as col_2_0_, account0_.EMAIL as col_3_0_ from account account0_
Hibernate: select account0_.ID as col_0_0_, account0_.USERNAME as col_1_0_, account0_.PASSWORD as col_2_0_, account0_.EMAIL as col_3_0_ from account account0_
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to de.Webshop.AccountManager.DataObjects.Account
    at de.Webshop.AccountManager.Startup.Main.main(Main.java:29)
 

mvitz

Top Contributor
Wieso gibst du beim dem HSQL Query immer alle Felder an?

Java:
...
public List<Account> getAllAccounts(Session session) {
        Transaction tx = session.beginTransaction();
        List<Account> accounts = session.createQuery("FROM Account").list();
        tx.commit();
        return accounts;
    }
...
 

mavinatic

Bekanntes Mitglied
weil ich sonst noch ne andere exception bekomme!

Wenn ich nur das object ausgeben lasse:

Java:
List<Account> list = connection.getAllAccounts(session);
        for(int i=0;i<list.size();i++) {
            System.out.println(list.get(i));
        }

funktionierts, wenn ich ne GET methode zb.: getUsername() dranhänge bekomm ich die exception!
 

mvitz

Top Contributor
Also bei mir funktioniert es. Habe jedoch testweise lediglich H2 und nicht MySQL als Datenbank genutzt. Ich habe zwei Vermutungen woran das liegen könnte.

1) Deine Hibernate Version (3.0.RC1) ist leicht veraltet, die neueste ist zur Zeit 3.5.4-Final.
2) Du nutzt anscheinend MySQL im MyISAM Modus (org.hibernate.dialect.MySQLMyISAMDialect) und MyISAM unterstützt keine Transaktionen. Versuch es doch einmal über den InnoDB Modus.
 

mavinatic

Bekanntes Mitglied
Hallo ihrs :)

Ich habe alles ausprobiert aber funktionierte NICHTS. Naja ich dachte mir nun ich fange einmal neu an und habe ein ganz simples tutorial genommen, welches ich auf meiner MYSQL Datenbank laufen lasse,... aber auch hier bekomme ich fehler ;)

FirstExample.java
Java:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


/**
 * @author Deepak Kumar
 *
 * [url=http://www.roseindia.net]JSP Tutorials,EJB Tutorial,JDBC Tutorials,Free Java Servlets Tutorials, WAP Tutorials, Spring Framework Tutorials, J2EE Tutorials, BioInformatics Tutorials, Java Server Faces Tutorials, Jboss Tutorials, Hibernate Tutorials, XML and MySQL Tutorials[/url]
 * Hibernate example to inset data into Contact table
 */
public class FirstExample {
  public static void main(String[] args) {
    Session session = null;

    try{
       SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
       session = sessionFactory.openSession();
 
        System.out.println("Inserting Record");
        Contact contact = new Contact();
        contact.setId(3);
        contact.setFirstName("Deepak");
        contact.setLastName("Kumar");
        contact.setEmail("deepak_38@yahoo.com");
        session.save(contact);
        System.out.println("Done");
    }catch(Exception e){
      System.out.println(e.getMessage());
    }finally{
//    	session.flush();
    	session.close();
      }
    
  }
}

Contact.hbm.xml
[XML]<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Contact" table="test"><!-- CLASSPATH -->
<id name="id" type="integer" column="id" >
<generator class="assigned"/>
</id>

<property name="firstName">
<column name="firstname" />
</property>
<property name="lastName">
<column name="lastname"/>
</property>
<property name="email">
<column name="email"/>
</property>
</class>
</hibernate-mapping>[/XML]

[XML]<?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="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/webshop</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
[/XML]

Was mach ich falsch ich hatte bisher Hibernate nur an Oracle und da gings eigentlich immer problemlos...Was mach ich falsch?

Den fehler den ich bekomme ist keiner! aber es wird nichts eingetragen!

Stacktrace:
Java:
12:43:29,212  INFO Environment:560 - Hibernate 3.3.2.GA
12:43:29,212  INFO Environment:593 - hibernate.properties not found
12:43:29,228  INFO Environment:771 - Bytecode provider name : javassist
12:43:29,228  INFO Environment:652 - using JDK 1.4 java.sql.Timestamp handling
12:43:29,369  INFO Configuration:1474 - configuring from resource: /hibernate.cfg.xml
12:43:29,369  INFO Configuration:1451 - Configuration resource: /hibernate.cfg.xml
12:43:29,478  INFO Configuration:600 - Reading mappings from resource : contact.hbm.xml
12:43:29,603  INFO HbmBinder:322 - Mapping class: Contact -> test
12:43:29,619  INFO Configuration:1589 - Configured SessionFactory: null
12:43:29,697  INFO DriverManagerConnectionProvider:64 - Using Hibernate built-in connection pool (not for production use!)
12:43:29,697  INFO DriverManagerConnectionProvider:65 - Hibernate connection pool size: 10
12:43:29,697  INFO DriverManagerConnectionProvider:68 - autocommit mode: false
12:43:29,712  INFO DriverManagerConnectionProvider:103 - using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost/webshop
12:43:29,728  INFO DriverManagerConnectionProvider:109 - connection properties: {user=root, password=****}
12:43:29,978  INFO SettingsFactory:114 - RDBMS: MySQL, version: 5.1.50-community
12:43:29,978  INFO SettingsFactory:115 - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-3.0.16-ga ( $Date: 2004/09/30 07:35:03 $, $Revision: 1.27.2.44 $ )
12:43:30,025  INFO Dialect:175 - Using dialect: org.hibernate.dialect.MySQLDialect
12:43:30,025  INFO TransactionFactoryFactory:59 - Using default transaction strategy (direct JDBC transactions)
12:43:30,040  INFO TransactionManagerLookupFactory:80 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
12:43:30,040  INFO SettingsFactory:161 - Automatic flush during beforeCompletion(): disabled
12:43:30,040  INFO SettingsFactory:165 - Automatic session close at end of transaction: disabled
12:43:30,040  INFO SettingsFactory:172 - JDBC batch size: 15
12:43:30,040  INFO SettingsFactory:175 - JDBC batch updates for versioned data: disabled
12:43:30,040  INFO SettingsFactory:180 - Scrollable result sets: enabled
12:43:30,040  INFO SettingsFactory:188 - JDBC3 getGeneratedKeys(): enabled
12:43:30,040  INFO SettingsFactory:196 - Connection release mode: auto
12:43:30,040  INFO SettingsFactory:220 - Maximum outer join fetch depth: 2
12:43:30,040  INFO SettingsFactory:223 - Default batch fetch size: 1
12:43:30,040  INFO SettingsFactory:227 - Generate SQL with comments: disabled
12:43:30,040  INFO SettingsFactory:231 - Order SQL updates by primary key: disabled
12:43:30,040  INFO SettingsFactory:235 - Order SQL inserts for batching: disabled
12:43:30,040  INFO SettingsFactory:397 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
12:43:30,056  INFO ASTQueryTranslatorFactory:47 - Using ASTQueryTranslatorFactory
12:43:30,056  INFO SettingsFactory:243 - Query language substitutions: {}
12:43:30,056  INFO SettingsFactory:248 - JPA-QL strict compliance: disabled
12:43:30,056  INFO SettingsFactory:253 - Second-level cache: enabled
12:43:30,056  INFO SettingsFactory:257 - Query cache: disabled
12:43:30,056  INFO SettingsFactory:382 - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
12:43:30,056  INFO SettingsFactory:267 - Optimize cache for minimal puts: disabled
12:43:30,056  INFO SettingsFactory:276 - Structured second-level cache entries: disabled
12:43:30,056  INFO SettingsFactory:296 - Echoing all SQL to stdout
12:43:30,056  INFO SettingsFactory:305 - Statistics: disabled
12:43:30,056  INFO SettingsFactory:309 - Deleted entity synthetic identifier rollback: disabled
12:43:30,056  INFO SettingsFactory:324 - Default entity-mode: pojo
12:43:30,056  INFO SettingsFactory:328 - Named query checking : enabled
12:43:30,150  INFO SessionFactoryImpl:193 - building session factory
12:43:30,462  INFO SessionFactoryObjectFactory:105 - Not binding factory to JNDI, no JNDI name configured
Inserting Record
Done
 
Zuletzt bearbeitet:

KSG9|sebastian

Top Contributor
ganz ehrlich: Kauf dir Buch und lern die Grundlagen.
Oder schau dir die umfangreiche Hibernate Dokumentation an, die ist wirklich gut und auch nicht so viel wie ein ganzes Buch.

Es hat wenig Sinn wenn du schon an so simplen Beispielen scheiterst.
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
I Hibernate / JPA: Eine Datenbank und pro User ein Schema Data Tier 9
T Hibernate/Spring JPA: eigene ID generieren Data Tier 5
Avalon @ManyToOne Hibernate oder JPA? Data Tier 5
D Hibernate Hibernate mit MariaDB Data Tier 1
ToBJo Hibernate Glassfish deploy mit Hibernate schlägt fehl Data Tier 1
C JPA Hibernate Map<String,String> richtig mappen Data Tier 2
S JPA Hibernate Search & EclipseLink (oder OpenJPA) Data Tier 0
R JPA Probleme mit Wechsel von EclipseLink auf Hibernate Data Tier 4
ARadauer Hibernate Entität readonly laden... Data Tier 1
G Hibernate SQL in Hibernate: Keine Parameter mit Index? Data Tier 2
P Wildfly + Hibernate + SQL Server Data Tier 0
E JPA Hibernate Query mit Timestamp hat seltsames Verhalten Data Tier 1
M Eclipse 4 RCP Hibernate Problem Data Tier 3
C Hibernate ProgressBar updaten mit Daten aus Hibernate Data Tier 4
B Hibernate und MySQL testen Data Tier 8
I Hibernate HQL: generiertes SQL ausgeben Data Tier 1
R mapping-file für hibernate zum Überschreiben der Annotationen Data Tier 7
R Hibernate Hibernate und Logback Data Tier 2
R Hibernate möchte Schema zwei mal undeployen Data Tier 2
F Hibernate Hibernate / JPA Data Tier 4
E Hibernate: Session vs EntityManager Data Tier 3
C Hibernate Hibernate Code Generation Data Tier 3
S Hibernate Mehrfachverbindung mit Hibernate Data Tier 3
M Hibernate Einstiegsfrage Data Tier 5
M Exception in thread "main" org.hibernate.MappingException: java.lang.ClassNotFoundException: Message Data Tier 4
S Hibernate Einstieg in Hibernate 3.2 sinnvoll? Data Tier 8
P JPA Eigene Vererbungsstrategie mit JPA / Hibernate Data Tier 2
J Hibernate Problem bei Master-Detail-Tabellen Data Tier 5
Y Jboss seam-hibernate-jpa Data Tier 5
RaoulDuke Hibernate Map<String,String> mit Annotations mappen Data Tier 2
M Hibernate Hibernate with GWT Data Tier 4
C Hibernate JPA mysql db erstellen Data Tier 4
M Hibernate Hibernate liest Daten zu oft aus! Data Tier 16
pg1337 Hibernate Fragen Data Tier 11
D Probleme bei Left Joins mit Hibernate createCriterias() Data Tier 2
D Hibernate probleme mit Verlinkungstabelle Data Tier 4
2 Hibernate Annotations Data Tier 7
G Hibernate select update no wait Data Tier 8
Z Hibernate: Many-To-Many nur eine bestimmte Spalte Data Tier 3
K Hibernate - Envers - Erzeugung der SQL Skripte Data Tier 4
G Hibernate 1:n Beziehung mit Vererbung Data Tier 5
D Hibernate-Criteria-API (Projections und MAX-Funktion) Data Tier 6
L Hibernate: failed to lazily initialize a collection of role Data Tier 3
S Hibernate hibernate.cfg.xml Data Tier 14
D JPA vs Hibernate.cfg und Entitymanager Data Tier 6
H Hibernate - Mapping für Enumeration Data Tier 1
R Hibernate Criteria Abfrageproblem Data Tier 2
A Hibernate und jdbc zusammen Data Tier 4
D Mit Hibernate aus JUnit ein DB-Schema erzeugen Data Tier 6
S [Hibernate] No Persistence provider for EntityManager Data Tier 5
B Problem mit org.hibernate.LazyInitializationException Data Tier 11
G Hibernate HQL und Interface Data Tier 4
G JSF Hibernate no session or session was closed Data Tier 12
T JPA2/Hibernate: Many-to-Many-Relation wird u.a. beim löschen nicht aktualisiert Data Tier 14
S (Hibernate) Mapping einer Datenbanktabelle mit mehreren Fremdschlüssel Data Tier 7
X [Hibernate] Zusammengesetzte Entities möglich? Data Tier 7
N Hibernate Fake? Data Tier 2
S Problem beim Insert mit Hibernate Data Tier 9
V Hibernate Projection Data Tier 2
T org.hibernate.impl.SessionFactoryImpl Memory Leak Data Tier 10
G Hibernate Composite key Data Tier 11
X [Hibernate] Connection Pool - MinSize ? Data Tier 2
R Hibernate Criteria OR Data Tier 2
T hibernate/jpa abgefragte Listen immer mit Null-Werten gefüllt Data Tier 8
X [Hibernate] Anderen Connection Pool - Vorschläge? Data Tier 3
ARadauer Hibernate DDL Loggen Data Tier 6
G Hibernate abfrage Collection Data Tier 3
X [Hibernate] ReverseEngineering - Eigene Strategy verwenden? Data Tier 3
R Hibernate Criteria .group größer als Data Tier 5
R Hibernate daten laden Data Tier 7
H [Hibernate]1:1 Beziehung Data Tier 8
H [Hibernate]No CurrentSessionContext configured! Data Tier 6
X [Hibernate] Lässt sich die Dauer eines SELECTs loggen? Data Tier 4
R Hibernate n:n Relationtabelle mit Date Data Tier 3
H [Hibernate] Unknown Entity Data Tier 3
H [Hibernate] Configuration Data Tier 3
C [Hibernate] Generierung von hbm.xml to Java Data Tier 4
lumo Eclipse & JPA & Hibernate & Derby Data Tier 5
J Zufallsauswahl aus ResultList bei JPA(Hibernate) / Performance Data Tier 3
M Hibernate: Datum 0001-01-01 erzeugt null-Datum Data Tier 4
G Datenbankzugriff mit Hibernate Data Tier 7
Y Hibernate - Angabe des Schemas Data Tier 6
LadyMilka (Hibernate) in Criteria implizierter Join durch Subquery's Data Tier 8
M Hibernate Mehr als 1 Object speichern? Data Tier 18
LadyMilka (Hibernate) subquery in FROM-Clause Data Tier 9
haemi Viele DTOs in hibernate IdentityMap Data Tier 3
LadyMilka (hibernate) UNION dem Dialekt hinzufügen Data Tier 3
M Hibernate + Oracle 10g XE Data Tier 3
lumo Hibernate - entity class not found Data Tier 5
P SQL PRoblem Hibernate? Data Tier 8
J Vererbung mit JPA / Hibernate - pro/contra Data Tier 3
T JBoss/Hibernate: Abfrage dauert lang + hohe CPU? Data Tier 19
7 Hibernate-Abfrage (SubSelect im FROM) Data Tier 2
G Hibernate: many-to-one - Verwaiste Datensätze löschen Data Tier 2
G Layer für Datenbankzugriff Hibernate Data Tier 5
G Hibernate Zwischentabelle Data Tier 2
Java.getSkill() Hibernate und Spalte vom Typ xml Data Tier 6
G Hibernate 0...1 : 1 Beziehung Data Tier 6
G Hibernate mehrere @oneToone Data Tier 2
G Hibernate 1:n, 1:1 Data Tier 26

Ähnliche Java Themen


Oben