# Hibernate Tutorial:  could not bind value?



## nocturne (17. Jan 2008)

Hi,

ich habe ein Tutorial von Hibernate und komme damit nicht klar: 

```
11:50:06,581  INFO Environment:514 - Hibernate 3.2.5
11:50:06,597  INFO Environment:547 - hibernate.properties not found
11:50:06,597  INFO Environment:681 - Bytecode provider name : cglib
11:50:06,612  INFO Environment:598 - using JDK 1.4 java.sql.Timestamp handling
11:50:06,753  INFO Configuration:1426 - configuring from resource: /hibernate.cfg.xml
11:50:06,753  INFO Configuration:1403 - Configuration resource: /hibernate.cfg.xml
11:50:07,284  INFO Configuration:553 - Reading mappings from resource : events/Event.hbm.xml
11:50:07,643  INFO HbmBinder:300 - Mapping class: events.Event -> EVENTS
11:50:07,705  INFO HbmBinder:1422 - Mapping collection: events.Event.participants -> PERSON_EVENT
11:50:07,721  INFO Configuration:553 - Reading mappings from resource : events/Person.hbm.xml
11:50:07,815  INFO HbmBinder:300 - Mapping class: events.Person -> PERSON
11:50:07,815  INFO HbmBinder:1422 - Mapping collection: events.Person.events -> PERSON_EVENT
11:50:07,815  INFO HbmBinder:1422 - Mapping collection: events.Person.emailAddresses -> PERSON_EMAIL_ADDR
11:50:07,830  INFO Configuration:1541 - Configured SessionFactory: null
11:50:08,002  INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
11:50:08,002  INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 1
11:50:08,002  INFO DriverManagerConnectionProvider:45 - autocommit mode: false
11:50:08,018  INFO DriverManagerConnectionProvider:80 - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/hibernate
11:50:08,018  INFO DriverManagerConnectionProvider:86 - connection properties: {user=server, password=****}
11:50:08,174  INFO SettingsFactory:89 - RDBMS: MySQL, version: 4.1.21-community-nt
11:50:08,174  INFO SettingsFactory:90 - JDBC driver: Mark Matthews' MySQL Driver, version: 2.0.14
11:50:08,205  INFO Dialect:152 - Using dialect: org.hibernate.dialect.MySQLDialect
11:50:08,221  INFO TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
11:50:08,221  INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
11:50:08,221  INFO SettingsFactory:143 - Automatic flush during beforeCompletion(): disabled
11:50:08,221  INFO SettingsFactory:147 - Automatic session close at end of transaction: disabled
11:50:08,221  INFO SettingsFactory:154 - JDBC batch size: 15
11:50:08,221  INFO SettingsFactory:157 - JDBC batch updates for versioned data: disabled
11:50:08,221  INFO SettingsFactory:162 - Scrollable result sets: enabled
11:50:08,221  INFO SettingsFactory:170 - JDBC3 getGeneratedKeys(): enabled
11:50:08,221  INFO SettingsFactory:178 - Connection release mode: auto
11:50:08,236  INFO SettingsFactory:202 - Maximum outer join fetch depth: 2
11:50:08,236  INFO SettingsFactory:205 - Default batch fetch size: 1
11:50:08,236  INFO SettingsFactory:209 - Generate SQL with comments: disabled
11:50:08,236  INFO SettingsFactory:213 - Order SQL updates by primary key: disabled
11:50:08,236  INFO SettingsFactory:217 - Order SQL inserts for batching: disabled
11:50:08,236  INFO SettingsFactory:386 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
11:50:08,236  INFO ASTQueryTranslatorFactory:24 - Using ASTQueryTranslatorFactory
11:50:08,236  INFO SettingsFactory:225 - Query language substitutions: {}
11:50:08,236  INFO SettingsFactory:230 - JPA-QL strict compliance: disabled
11:50:08,236  INFO SettingsFactory:235 - Second-level cache: enabled
11:50:08,236  INFO SettingsFactory:239 - Query cache: disabled
11:50:08,236  INFO SettingsFactory:373 - Cache provider: org.hibernate.cache.NoCacheProvider
11:50:08,236  INFO SettingsFactory:254 - Optimize cache for minimal puts: disabled
11:50:08,236  INFO SettingsFactory:263 - Structured second-level cache entries: disabled
11:50:08,252  INFO SettingsFactory:283 - Echoing all SQL to stdout
11:50:08,252  INFO SettingsFactory:290 - Statistics: disabled
11:50:08,252  INFO SettingsFactory:294 - Deleted entity synthetic identifier rollback: disabled
11:50:08,252  INFO SettingsFactory:309 - Default entity-mode: pojo
11:50:08,252  INFO SettingsFactory:313 - Named query checking : enabled
11:50:08,330  INFO SessionFactoryImpl:161 - building session factory
11:50:09,001  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
11:50:09,017  INFO SchemaExport:154 - Running hbm2ddl schema export
11:50:09,017 DEBUG SchemaExport:170 - import file not found: /import.sql
11:50:09,017  INFO SchemaExport:179 - exporting generated schema to database
11:50:09,017 DEBUG SchemaExport:303 - alter table PERSON_EMAIL_ADDR drop foreign key FKA54215FE7708282F
11:50:09,189 DEBUG SchemaExport:303 - alter table PERSON_EVENT drop foreign key FKAD91D910F96D1A45
11:50:09,329 DEBUG SchemaExport:303 - alter table PERSON_EVENT drop foreign key FKAD91D9107708282F
11:50:09,454 DEBUG SchemaExport:303 - drop table if exists EVENTS
11:50:09,486 DEBUG SchemaExport:303 - drop table if exists PERSON
11:50:09,517 DEBUG SchemaExport:303 - drop table if exists PERSON_EMAIL_ADDR
11:50:09,532 DEBUG SchemaExport:303 - drop table if exists PERSON_EVENT
11:50:09,564 DEBUG SchemaExport:303 - create table EVENTS (EVENT_ID bigint not null auto_increment, EVENT_DATE datetime, title varchar(255), primary key (EVENT_ID))
11:50:09,626 DEBUG SchemaExport:303 - create table PERSON (PERSON_ID bigint not null auto_increment, age integer, firstname varchar(255), lastname varchar(255), primary key (PERSON_ID))
11:50:09,689 DEBUG SchemaExport:303 - create table PERSON_EMAIL_ADDR (PERSON_ID bigint not null, EMAIL_ADDR varchar(255))
11:50:09,767 DEBUG SchemaExport:303 - create table PERSON_EVENT (EVENT_ID bigint not null, PERSON_ID bigint not null, primary key (PERSON_ID, EVENT_ID))
11:50:09,829 DEBUG SchemaExport:303 - alter table PERSON_EMAIL_ADDR add index FKA54215FE7708282F (PERSON_ID), add constraint FKA54215FE7708282F foreign key (PERSON_ID) references PERSON (PERSON_ID)
11:50:09,954 DEBUG SchemaExport:303 - alter table PERSON_EVENT add index FKAD91D910F96D1A45 (EVENT_ID), add constraint FKAD91D910F96D1A45 foreign key (EVENT_ID) references EVENTS (EVENT_ID)
11:50:10,095 DEBUG SchemaExport:303 - alter table PERSON_EVENT add index FKAD91D9107708282F (PERSON_ID), add constraint FKAD91D9107708282F foreign key (PERSON_ID) references PERSON (PERSON_ID)
11:50:10,251  INFO SchemaExport:196 - schema export complete
Exception in thread "main" java.lang.NullPointerException
	at org.hibernate.jdbc.AbstractBatcher.closePreparedStatement(AbstractBatcher.java:534)
	at org.hibernate.jdbc.AbstractBatcher.closeStatement(AbstractBatcher.java:269)
	at org.hibernate.id.insert.AbstractReturningDelegate.releaseStatement(AbstractReturningDelegate.java:58)
	at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:36)
	at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
	at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
	at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
	at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
	at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
	at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
	at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
	at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)
	at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
	at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
	at $Proxy0.save(Unknown Source)
	at events.EventManager.createAndStoreEvent(EventManager.java:50)
	at events.EventManager.main(EventManager.java:15)
Hibernate: insert into EVENTS (EVENT_DATE, title) values (?, ?)
11:50:10,532  INFO TimestampType:140 - could not bind value '2008-01-17 11:50:06' to parameter: 1; null
```
Sind die Meldungen!

hier die hivernate.cfg.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="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
        <property name="connection.username">xxx</property>
        <property name="connection.password">xxx<property>

        
        <property name="connection.pool_size">1</property>

        
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        
        <property name="current_session_context_class">thread</property>

        
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        
        <property name="show_sql">true</property>

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

        <mapping resource="events/Event.hbm.xml"/>
        <mapping resource="events/Person.hbm.xml"/>

    </session-factory>

</hibernate-configuration>
```

hier die Main-Klasse:


```
package events;
import org.hibernate.*;
import org.hibernate.criterion.Expression;

import java.util.*;

import util.HibernateUtil;

public class EventManager {

    public static void main(String[] args) {
        EventManager mgr = new EventManager();

        if (args[0].equals("store")) {
            mgr.createAndStoreEvent("My Event", new Date());
        }
        else if (args[0].equals("list")) {
            List events = mgr.listEvents();
            for (int i = 0; i < events.size(); i++) {
                Event theEvent = (Event) events.get(i);
                System.out.println("Event: " + theEvent.getTitle() +
                                   " Time: " + theEvent.getDate());
            }
        }
        else if (args[0].equals("addpersontoevent")) {
            Long eventId = mgr.createAndStoreEvent("My Event", new Date());
            Long personId = mgr.createAndStorePerson("Foo", "Bar");
            mgr.addPersonToEvent(personId, eventId);
            System.out.println("Added person " + personId + " to event " + eventId);
        }
        else if (args[0].equals("addemailtoperson")) {
            Long personId = mgr.createAndStorePerson("Foozy", "Beary");
            mgr.addEmailToPerson(personId, "foo@bar");
            mgr.addEmailToPerson(personId, "bar@foo");
            System.out.println("Added two email addresses (value typed objects) to person entity : " + personId);
        }

        HibernateUtil.getSessionFactory().close();
    }

    private Long createAndStoreEvent(String title, Date theDate) {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Event theEvent = new Event();
        theEvent.setTitle(title);
        theEvent.setDate(theDate);

        session.save(theEvent);

        session.getTransaction().commit();

        return theEvent.getId();
    }

    private Long createAndStorePerson(String firstname, String lastname) {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Person thePerson = new Person();
        thePerson.setFirstname(firstname);
        thePerson.setLastname(lastname);

[b]        session.save(thePerson);[/b]

        session.getTransaction().commit();

        return thePerson.getId();
    }


    private List listEvents() {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        List result = session.createQuery("from Event").list();

        session.getTransaction().commit();

        return result;
    }

    private void addPersonToEvent(Long personId, Long eventId) {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Person aPerson = (Person) session
                .createQuery("select p from Person p left join fetch p.events where p.id = :pid")
                .setParameter("pid", personId)
                .uniqueResult(); // Eager fetch the collection so we can use it detached

        Event anEvent = (Event) session.load(Event.class, eventId);
        // If we want to handle it bidirectional and detached, we also need to load this
        // collection with an eager outer-join fetch, this time with Criteria and not HQL:
        /*
        Event anEvent = (Event) session
                .createCriteria(Event.class).setFetchMode("participants", FetchMode.JOIN)
                .add( Expression.eq("id", eventId) )
                .uniqueResult(); // Eager fetch the colleciton so we can use it detached
        */

        session.getTransaction().commit();

        // End of first unit of work

        aPerson.getEvents().add(anEvent); // aPerson is detached
        // or bidirectional safety method, setting both sides: aPerson.addToEvent(anEvent);

        // Begin second unit of work

        Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
        session2.beginTransaction();

        session2.update(aPerson); // Reattachment of aPerson

        session2.getTransaction().commit();
    }

    private void addEmailToPerson(Long personId, String emailAddress) {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Person aPerson = (Person) session.load(Person.class, personId);

        // The getEmailAddresses() might trigger a lazy load of the collection
        aPerson.getEmailAddresses().add(emailAddress);

        session.getTransaction().commit();
    }

}
```


----------



## SlaterB (17. Jan 2008)

hat offensichtlich was mit '2008-01-17 11:50:06' zu tun, wo kommt dieser Wert her?,
läuft da irgendein Import/ Export ab?
welche Klasse ist betroffen, wie ist das Mapping/ das DB-Schema dazu?

kannst du ohne irgendwelche automatischen Skripte ganz zivilisiert Date schreiben/ lesen?
wenn du da nur Start-Skripts ausführst und nix weiter machen kannst,
dann musst du wohl erstmal auf alle Date-Spalten verzichten,
bis du das ganz in Ruhe testen kannst

(vielleicht hat aber auch wer gleich ne schnelle Lösung  )


----------



## nocturne (17. Jan 2008)

Wo's herkommt? Guck mal Zeile 27 der EventManager-Klasse die ich gepostet habe!

Den Quellcode von Hibernate wollte ich nicht umschreiben.
Weder ein Import noch ein Export.
Hier das Bean: 

```
package events;

import java.util.*;

public class Event {
    private Long id;

    private String title;
    private Date date;

    public Event() {}

    public Long getId() {
        return id;
    }

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

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
    

    private Set participants = new HashSet();

    public Set getParticipants() {
        return participants;
    }

    public void setParticipants(Set participants) {
        this.participants = participants;
    }

}
```

IMOW dieses Mapping: 

```
<?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="events.Event" table="EVENTS">
        <id name="id" column="EVENT_ID">
            <generator class="native"/>
        </id>
        <property name="date" type="timestamp" column="EVENT_DATE"/>
        <property name="title"/>

        <set name="participants" table="PERSON_EVENT" inverse="true">
            <key column="EVENT_ID"/>
            <many-to-many column="PERSON_ID" class="events.Person"/>
        </set>

    </class>


</hibernate-mapping>
```


Keine Start-Skripte!. 
Das ausführen des querys: 
insert into EVENTS (EVENT_DATE, title) values (2008-01-17 11:50:06, '') 
funktioniert nicht, das Ausführen des Querys: 
insert into EVENTS (EVENT_DATE, title) values ('2008-01-17 11:50:06', '') 
dagegen klappt. 

Ohne Date-Feld gehts ja, ist aber scheixxe.


----------



## SlaterB (17. Jan 2008)

ohne Anführungszeichen geht in SQL und HQL wenig, richtig,

zum Date:
warum im Mapping timestamp? versuche mal date oder ganz weglassen:
<property name="date" column="EVENT_DATE"/> 
dann findet Hibernate vielleicht automatisch das richtige


----------



## nocturne (17. Jan 2008)

SlaterB hat gesagt.:
			
		

> ohne Anführungszeichen geht in SQL und HQL wenig, richtig,
> 
> zum Date:
> warum im Mapping timestamp? versuche mal date oder ganz weglassen:
> ...


Ergebnis: could not bind value '17 Januar 2008'


Geht nicht mal in die richtige Richtung! Ich will auf Timestamp nicht verzichten!


----------



## ms (17. Jan 2008)

Meine Vermuntung: du erzeugst nirgend wo ein Timestamp-Objekt.

ms


----------



## SlaterB (17. Jan 2008)

warum dann die Fehlermeldung mit einem genauen Datumsstring?
der Quelltext ist auch recht eindeutig

tja, das DB-Schema sollte wohl nicht mehr die große Rolle spielen,
wenn 
insert into EVENTS (EVENT_DATE, title) values ('2008-01-17 11:50:06', '') 
funktioniert, Tippfehler bei Spaltennamen sind dann auch ausgeschlossen,

bei google nix zu finden,
mir fällt nix mehr ein außer Pech mit der Datenbank/ Treiber oder so


----------



## maki (17. Jan 2008)

Also ich würde mir mehr logging infos von Hibernate geben lassen 

http://www.hibernate.org/hib_docs/reference/en/html/session-configuration.html#configuration-logging


----------



## ms (17. Jan 2008)

maki hat gesagt.:
			
		

> Also ich würde mir mehr logging infos von Hibernate geben lassen


Manch einer würde vielleicht auch den Debugger anwerfen ... :lol: 

ms


----------



## tfa (17. Jan 2008)

ms hat gesagt.:
			
		

> Manch einer würde vielleicht auch den Debugger anwerfen ... :lol:


 :lol:


----------



## nocturne (17. Jan 2008)

Entwarnung !!!!!

ich hab den JConnector/jdbc aktualisiert. ES GEHT.


----------



## byte (17. Jan 2008)

Lesbarkeit = null in diesem Thread dank Log-Quote. Mit Debugging wär das nicht passiert. :bae:

Edit: Nun wurde es rausgelöscht.  :lol:


----------



## ms (17. Jan 2008)

@nocturen
Könntest du bitte die 3km-Lange Konsoleninformation wieder aus deinem Beitrag rausnehmen.
Danke.

Das mit dem Debuggen war ein Scherz.
Du sollst dass Loglevel auf Debug stellen.
Und vielleicht kannst du auch mal das erzeugte create-Statement ausgeben.

edit:
Hat sich mittlerweile ja erledigt.

ms


----------



## maki (17. Jan 2008)

ROFL 

:lol:  :lol:  :lol:


----------



## SlaterB (17. Jan 2008)

Treiber, sag ich doch


----------



## nocturne (18. Jan 2008)

@ms: Wollte gerade das Logging rauslöschen! 
Zum Create statement: Das wurde ja ausgegeben, du meintest warscheinlich das "insert"-Statement?
@byto: Logglevel "Debug" reichte nicht aus, ich habe das Insert-Statement trotzdem nicht gefunden. Deshalb auf eine stufe weiter!

@SlaterB: Jo, der Treiber.


----------

