IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Hibernate Java Discussion :

erreur d'éxécution pour un programme du tutoriel Hibernate


Sujet :

Hibernate Java

  1. #1
    Membre actif
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    729
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 729
    Points : 250
    Points
    250
    Par défaut erreur d'éxécution pour un programme du tutoriel Hibernate
    Bonjour,
    je suis le tutoriel Hibernate et ai une erreur d'éxécution incompréhensible pour moi.
    Je résume la situation : voici l'organisation de mes fichiers :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
     
    .
    +lib
      <Hibernate and third-party libraries>
    +src
      +events
        Event.java
        Person.java
        EventManager.java    (là où est la classe main)!
        Event.hbm.xml
        Person.hbm.xml
      +util
        HibernateUtil.java
      hibernate.cfg.xml
    +data
    build.xml
    Voici mon fichier Event.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
     
    package events;
     
    import java.util.Date;
     
    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;
        }
    etc.........
    }
    Voici mon fichier Person.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
     
    package events;
    import java.util.* ;
    public class Person {
     
        private Long id;
        private int age;
        private String firstname;
        private String lastname;
        private Set events = new HashSet() ;
     
        public Person() {}
     
        // Accessor methods for all properties, private setter for 'id'
        public Long getId() {
            return id;
        }
     
        private void setId(Long id) {
            this.id = id;
        }
        public int getAge()
        {
    	return age;
        }
        public void setAge(int age)
        {
    	this.age = age;
        }
        public String getFirstname()
        {
    	return firstname;
        }
        public void setFirstname(String firstname)
        {
    	this.firstname = firstname ;
        }
        public String getLastname()
        {
    	return lastname;
        }
        public void setLastname(String lastname)
        {
    	this.lastname = lastname ;
        }
        public Set getEvents() {
            return events;
        }
     
        public void setEvents(Set events) {
            this.events = events;
        }
     
    }
    Voici mon fichier EventManager.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
     
    package events;
    import org.hibernate.Session;
     
    import java.util.Date;
    import java.util.List;
    import java.lang.Long ;
     
    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);
            	HibernateUtil.getSessionFactory().close();
        	}
        }
        private Long createAndStoreEvent(String title, Date theDate) {
     
    	Long eventId ;
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
     
            session.beginTransaction();
     
            Event theEvent = new Event();
            theEvent.setTitle(title);
            theEvent.setDate(theDate);
     
            eventId = (Long) session.save(theEvent);
     
            session.getTransaction().commit();
    	return eventId ;
        }
        private Long createAndStorePerson(String firstname, String lastname) {
     
    	Long personId ;
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
     
            session.beginTransaction();
     
            Person thePerson = new Person();
            thePerson.setFirstname(firstname);
            thePerson.setLastname(lastname);
     
            personId = (Long) session.save(thePerson);
     
            session.getTransaction().commit();
    	return personId ;
        }
        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.load(Person.class, personId);
        	Event anEvent = (Event) session.load(Event.class, eventId);
     
        	aPerson.getEvents().add(anEvent);
     
        	session.getTransaction().commit();
        }
     
     
    }
    Mon fichier hibernateUtil.java est le suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
     
    package util;
     
    import org.hibernate.*;
    import org.hibernate.cfg.*;
     
    public class HibernateUtil {
     
        private static final SessionFactory sessionFactory;
     
        static {
            try {
                // Create the SessionFactory from hibernate.cfg.xml
                sessionFactory = new Configuration().configure().buildSessionFactory();
            } catch (Throwable ex) {
                // Make sure you log the exception, as it might be swallowed
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
     
        public static SessionFactory getSessionFactory() {
            return sessionFactory;
        }
     
    }
    Le fichier de mapping Event.hbm.xml est le suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
     
    <?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"/>
        </class>
     
    </hibernate-mapping>
    Le fichier de mapping Person.hbm.xml est le suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
     
    <?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.Person" table="PERSON">
            <id name="id" column="PERSON_ID">
                <generator class="native"/>
            </id>
            <property name="age"/>
            <property name="firstname"/>
            <property name="lastname"/>
        </class>
     
        <set name="events" table="PERSON_EVENT">
            <key column="PERSON_ID"/>
            <many-to-many column="EVENT_ID" class="events.Event"/>
        </set>
     
    </hibernate-mapping>
    Le fichier de configuration hibernate hibernate.cfg.xml est le suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
     
    <?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>
     
            <!-- Database connection settings -->
            <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
            <property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
            <property name="connection.username">sa</property>
            <property name="connection.password"></property>
     
            <!-- JDBC connection pool (use the built-in) -->
            <property name="connection.pool_size">1</property>
     
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
     
            <!-- Enable Hibernate's automatic session context management -->
            <property name="current_session_context_class">thread</property>
     
            <!-- Disable the second-level cache  -->
            <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
     
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
     
            <!-- Drop and re-create the database schema on startup -->
            <!--property name="hbm2ddl.auto"createproperty-->
     
            <mapping resource="events/Event.hbm.xml"/>
    	<mapping resource="events/Person.hbm.xml"/>
        </session-factory>
     
    </hibernate-configuration>
    Voilà pour ce qui est de la présentation. Maintenant, voici le message d'erreurs que j'ai eu :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    [java] 08:07:14:421 ERROR XMLHelper:61 - Error parsing XML: XML InputStream(22) The content of element type "hibernate-mapping" must match "(meta*,typedef*,import*,(class|subclass|joinedsubclass|union-subclass)*,resultset*,(query|sql-query)*,filter-def*,database-object*)"
    [java] Initial SessionFactory creation failed.org.hibernate. InvalidMappingException: could not parse mapping document from ressource event/Person.hbm.xml
    [java] java.lang.ExceptionInInitializerError
    [java] at util.HibernateUtil.<clinit>(Unknown Source)
    [java] at events.EventManager.createAndStoreEvent(Unknown Source)
    [java] at events.EventManager.main(Unknown Source)
    [java] Caused by:org.hibernate.InvalidMappingException: Could not parse mapping document from ressource events/Person.hbm.xml
    [java]  ...........
    [java] Caused by:org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping
    [java]   ............
    [java] Caused by: org.xml.sax.SAXParseException: The content of element type "hibernate-mapping" must match "(meta*,typedef*,import*,(class|subclass|joined-subclass|union-subclass)*,resultset*,(query|sql-query)*,filter-def*,database-object*)".
    [java]   ..........
    [java] Exception in thread "main"
    Est-ce que quelqu'un peut me dire où est l'erreur ? Il semble qu'il s'agisse de parser le fichier de mapping Person.hbm.xml, mais je n'y comprend rien. Merci d'avance de votre aide.
    Par la même occasion je voudrais rediriger les informations de sortie soit de la compilation, soit de l'éxécution vers un autre fichier. Mon fichier "Ant" d'automatisation "build.xml" des tâches est le suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
        <target name="compile" depends="clean, copy-resources">
          <javac srcdir="${sourcedir}"
                 destdir="${targetdir}"
                 classpathref="libraries"/>
        </target>
     
        <target name="run" depends="compile">
            <java fork="true" classname="events.EventManager" classpathref="libraries">
                <classpath path="${targetdir}"/>
                <arg value="${action}"/>
            </java>
        </target>
    Comment faut-il que je fasse pour rediriger les sorties vers un fichier "sortie" ?
    Merci de répondre à cette deuxième question.
    Xavier

  2. #2
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    Dans ton fichier Person.hbm.xml, la partie concernant ton "set" doit être comprise entre les balises "<class>" et "</class>"

  3. #3
    Membre actif
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    729
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 729
    Points : 250
    Points
    250
    Par défaut réponse
    bonjour,
    et merci de ta réponse. En effet, ca marche mais j'ai une autre erreur d'éxécution. Avant de t'en parler, saurais-tu rediriger les informations de sortie de compilation et d'éxécution dans un fichier que je nommerai "sortie" par exemple ?
    Mon fichier build.xml (de "Ant") se présente sous la forme suivante :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
        <target name="compile" depends="clean, copy-resources">
          <javac srcdir="${sourcedir}"
                 destdir="${targetdir}"
                 classpathref="libraries"/>
        </target>
     
        <target name="run" depends="compile">
            <java fork="true" classname="events.EventManager" classpathref="libraries">
                <classpath path="${targetdir}"/>
                <arg value="${action}"/>
            </java>
        </target>

  4. #4
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    Je ne connais pas de tête la manière de faire, mais un petit tour sur le site de Ant, et tu devrais avoir la réponse.

  5. #5
    Membre actif
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    729
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 729
    Points : 250
    Points
    250
    Par défaut nouvelle erreur d'éxécution
    Rebonjour,
    j'ai cette fois une nouvelle erreur qui est la suivante :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    [java] 10:52:44:390 ERROR JDBCExceptionReporter:78 - Table not found in statement [insert into (PERSON_ID, age, firstname, lastname) values (null, ?, ?, ?)]
    [java] Exception in thread "main"
    J'ai l'impression que ça vient de la ligne suivante du fichier de configuration hibernate hibernate.cfg.xml :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
     
    <?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>
     
            <!-- Database connection settings -->
             ........ 
            <!-- Drop and re-create the database schema on startup -->
            <!--property name="hbm2ddl.auto"createproperty-->
             .........
         </session-factory>
     
    </hibernate-configuration>
    En effet, je l'ai désactivé antérieurement pour pouvoir créer plus de lignes dans la table EVENT sans que ca réinitialise la table. Faudrait-il que pour éviter mon erreur d'éxécution je revalide la ligne de la sorte ? :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
            <!-- Drop and re-create the database schema on startup -->
            <property name="hbm2ddl.auto">create</property>
    Si j'ai bien compris cette instruction permet de créer toutes les tables déclarées dans les fichiers de mapping ? est-ce exact ?
    Merci de ta réponse.
    Xavier

  6. #6
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    Oui, ça permet de créer les tables.
    Il y a également d'autres options, selon tes besoins: update, create-drop...
    A confirmer en lisant la doc.

Discussions similaires

  1. Erreur de compilation (pour tous les programmes)
    Par LittleWhite dans le forum Qt
    Réponses: 10
    Dernier message: 28/11/2010, 12h46
  2. erreur dans l'éxécution d'un programme
    Par chlab dans le forum Caml
    Réponses: 1
    Dernier message: 07/06/2010, 22h09
  3. Rapport d'erreurs Windows pour crash programme C++.
    Par elraton dans le forum Windows
    Réponses: 7
    Dernier message: 02/02/2010, 11h47
  4. Erreur d'éxécution d'une macro pour renommer un onglet
    Par cuterate dans le forum Macros et VBA Excel
    Réponses: 6
    Dernier message: 29/10/2009, 11h38
  5. Réponses: 6
    Dernier message: 24/09/2007, 22h34

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo