These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: netbeans 5.5 + hibernate 3.2 probleme pour un exemple simple
PostPosted: Tue Mar 20, 2007 11:44 am 
Newbie

Joined: Mon Mar 19, 2007 1:07 pm
Posts: 3
bonjour
j'ai un petit probleme avec netbeans et hibernate malgré les tuto et le livre...
et j'ai déja chercher sur les forum et sur google ( plusieurs jours déja )
je suis déja à 2 semaine de java a temps plein

Environement:
Netbeans 5.5 -> environement choisi pour le projet
hibernate 3.2
MySQL 5.0 -> base de données choisi par le projet

edit:

je pense avoir trouver une piste pour probleme décrit ci dessous :
en regardant les log j'ai vu qu'il n'arrive pas a trouver le fichier de conf
dans netbeans on doit le mettre ou ?

Code:
log4j:WARN No appenders could be found for logger (org.apache.commons.digester.Digester.sax).
log4j:WARN Please initialize the log4j system properly.
20 mars 2007 17:14:00 org.apache.catalina.core.StandardContext start
INFO: Le conteneur org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/test] a déjà été démarré
Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found


fin edit


je travail sur un exemple tout simple décrit beaucoup plus en détails ci dessous.
je dois signaler que mysql marche bien mais j'ai un doute sur la connexion entre hibernate et mysql ainsi que sur les paths des différents fichier a mettre en place

quelqu'un pourrais t'il m'indiquer les étapes et les repertoires où mettre mes différents fichiers parce que je ne comprend pas pourquoi cela ne marche pas
( message d'erreur tout a la fin )

par avance merci au gens qui voudront m'aider et le pourront



dans la config de netbeans :

Dois je ajouter le driver MySQL dans Netbeans ? ( runtime -> drivers )
Ou est ce que je dois ajouter directement une data source via interface web dans http://localhost:8084/admin/ -> ressources -> une datasource

je dois dire que j'ai fait les deux successivement sans succes avec hibernate !
Par contre les ptit script normaux de connexion à une base de données marche.

Description de mes fichiers :

BASE DE DONNEES
user : toto
pass : toto
base : test
table : toto que j'ai rempli de quelque ligne

Code:
CREATE TABLE `toto` (
  `id` int(10) NOT NULL auto_increment,
  `nom` varchar(20) NOT NULL default 'toto',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8




NETBEANS
Nom du projet : test
type : application web
option particuliere :
l'option Set Source level to 1.4 est décoché
l'option JSF est coche, j'ai gardé la config donnée par défaut

Librairies:

nom: hibernate-mysql
contenu :
hibernate3.jar
mysql-connector-java-5.0.4-bin.jar
+ la liste ci dessous

liste des lib du tar.gz
Code:
_README.txt                     jaas.jar
ant-1.6.5.jar                   jaas.licence.txt
ant-antlr-1.6.5.jar             jacc-1_0-fr.jar
ant-junit-1.6.5.jar             javassist.jar
ant-launcher-1.6.5.jar          jaxen-1.1-beta-7.jar
ant-swing-1.6.5.jar             jboss-cache.jar
antlr-2.7.6.jar                 jboss-common.jar
antlr.license.txt               jboss-jmx.jar
apache.license-2.0.txt          jboss-system.jar
apache.license.txt              jdbc2_0-stdext.jar
asm-attrs.jar                   jdbc2_0-stdext.licence.txt
asm.jar                         jgroups-2.2.8.jar
c3p0-0.9.1.jar                  jta.jar
c3p0.license.txt                jta.licence.txt
cglib-2.1.3.jar                 junit-3.8.1.jar
checkstyle-all.jar              log4j-1.2.11.jar
cleanimports.jar                oscache-2.1.jar
commons-collections-2.1.1.jar   proxool-0.8.3.jar
commons-logging-1.0.4.jar       swarmcache-1.0rc2.jar
concurrent-1.3.2.jar            syndiag2.jar
connector.jar                   version.properties
connector.licence.txt           versioncheck.jar
dom4j-1.6.1.jar                 xerces-2.6.2.jar
ehcache-1.2.3.jar               xml-apis.jar



JAVA CODE mis dans le meme package

pakage : essai

Class Toto : toto.java
Code:
package essai;

public class Toto
{
    public Toto(){}
   
    private Integer id;
    private String nom;
   
    public Integer getId() { return id; }
    private void setId(Integer id) { this.id = id; }

    public String getNom() { return nom; }
    public void setNom(String nom){ this.nom = nom; }
}


servlet : voir.java
desc : afficher les elements (code recuperer et adapter du tuto officiel)
Code:
package essai;

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.util.*;
import java.text.SimpleDateFormat;
import essai.HibernateUtil;

public class voir extends HttpServlet {
    protected void doGet(HttpServletRequest request,HttpServletResponse response)
    throws ServletException, IOException
    {
        try {
            HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
            PrintWriter out = response.getWriter();
            List result = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(Toto.class).list();
            if (result.size() > 0) {
                for (Iterator it = result.iterator(); it.hasNext();) {
                    Toto toto = (Toto) it.next();
                    out.println("<p>");
                    out.println("<br />id : " + toto.getId() );
                    out.println("<br />nom: " + toto.getNom() );
                    out.println("</p>");
                }
            }
            out.flush();
            out.close();
            HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
        }
        catch (Exception ex)
        {
            HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
            throw new ServletException(ex);
        }
    }
}


Class: HibernateUtil.java
desc: une classe qui aide a la connexion à hibernate si j'ai saisi
Code:
package essai;

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;
    }
}



XML -> je ne sais pas ou les mettres

config : hibernate.cfg.xml -> je l'ai mis dans WEB-INF sans succes et puis dans le package essai mais sans succes tjs
Code:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">toto</property>
        <property name="hibernate.connection.password">toto</property>
        <property name="show_sql">true</property>
       
         <!-- mapping de base-->
         <mapping resource="java/essai/Toto.hbm.xml"/>
       
    </session-factory>
</hibernate-configuration>



config : Toto.hbm.xml -> je l'ai mis dans le package essai
Code:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
       
       
<hibernate-mapping>

    <class name="Toto" table="toto">
        <id name="id" column="id">
            <generator class="increment"/>
        </id>
        <property name="nom" column="nom"/>
    </class>

</hibernate-mapping>



enfin voila cela m'affiche ceci comme erreur

Code:
exception

javax.servlet.ServletException: L'exécution de la servlet a lancé une exception
   org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)

cause mère

java.lang.NoClassDefFoundError
   essai.voir.doGet(voir.java:20)
   javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
   javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
   org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)



merci aux gens qui voudront m'aider et le pourront

cordialement

mathieu


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 21, 2007 3:53 am 
Expert
Expert

Joined: Thu Sep 04, 2003 8:23 am
Posts: 368
Ton fichier hibernate.cfg.xml doit se trouver dans WEB-INF/classes soit dans le classpath (à la racine).
Je n'utilise pas netbeans donc je ne sais pas quelle est la bonne pratique pour mettre les fichiers comme cela. Tu peux essayer de le mettre à la racine de ton src pour qu'il soit copié dans WEB-INF/classes

_________________
Seb
(Please don't forget to give credits if you found this answer useful :)


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 21, 2007 6:05 am 
Newbie

Joined: Mon Mar 19, 2007 1:07 pm
Posts: 3
en fait non cela ne marche pas merci quand meme ;-)

je l'ai mis dans src/java/ et maintenant il lis le fichier hibernate.cfg.xml
cela fonctionne sur netbeans 5.5, c'est pas tres propres car dans l'arborescence de projet il me l'affiche dans les package par défaut.

j'ai un autre soucis par contre il m'indique maintenant dans les log de tomcat:

Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource ./essai/Toto.hbm.xml

une idée ?? je comprend que c'est un probleme au niveau de l'interpretation du mapping xml. A mon avis le mapping doit pas etre bon.

j'ai fait quelque modification par rapport au message d'avant :

hibernate.cfg.xml
Code:
         <!-- mapping de base-->
         <mapping resource="./essai/Toto.hbm.xml"/>


le mapping de toto est :

Toto.hbm.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="Toto" table="toto">
        <id name="id" column="id" type="int">
            <generator class="increment"/>
        </id>
        <property name="nom" column="nom"/>
    </class>
</hibernate-mapping>



la table toto est celle ci
toto.sql
Code:
CREATE TABLE `toto` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `nom` varchar(20) NOT NULL default 'toto',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


bon je continue a chercher si je trouve des idées je vous tiens au courrant

merci a ceux qui m'aide

cordialement mathieu


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 21, 2007 9:04 am 
Expert
Expert

Joined: Thu Sep 04, 2003 8:23 am
Posts: 368
Tout ce que tu mets dans src/java va être mis dans le classpath de ta webapp par netbeans je pense.

Du coup ton fichier Toto.hbm.xml doit se trouver dans sr/java/essai

_________________
Seb
(Please don't forget to give credits if you found this answer useful :)


Top
 Profile  
 
 Post subject:
PostPosted: Wed Apr 04, 2007 11:54 am 
Newbie

Joined: Wed Apr 04, 2007 11:47 am
Posts: 4
Bonjour,

J'ai eu le même problème que toi en suivant le getting started d'Hibernate:
Code:
[java] Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource events/Event.hbm.xml


J'ai trouvé le problème, il vient du fichier de mapping. Celui ci doit préciser son package :
<hibernate-mapping package="events">

Pour ton cas je suppose que ce serai le package "essai".



English version :

You may obtain the following error when following the tutorial :

Code:
[java] Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource events/Event.hbm.xml


To solve this you must specify the package in the mapping file :
<hibernate-mapping package="events">


Top
 Profile  
 
 Post subject:
PostPosted: Wed Apr 04, 2007 12:20 pm 
Newbie

Joined: Mon Mar 19, 2007 1:07 pm
Posts: 3
merci bcp
j'ai un peu abandonné hibernate ces derniers temps mais je pense reprendre ce travail de configuration d'ici quelques semaines

merci de m'indiqué les corrections.

je viens de changer la base du projet java sur lequel je travaille, j'utilise desormais postgresql :-)
peut etre bientot un un tuto rire si cela fonctionne... ou un nouveau rapport de beug dans le cas contraitre.

a bientot


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.