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 :

Tomcat hibernate annotation DAO probleme mapping


Sujet :

Hibernate Java

  1. #1
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut Tomcat hibernate annotation DAO probleme mapping
    Bonjour,
    je debut avec hibernate. j'ai fait une tuto sur herbernate 3 avec le fichier de Mapping et les DAO ca marche. Mais maintement je veut faire le meme tuto avec les annotations et utiliser les DAO ça ne marche plus il me donne

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
       Exception in thread "main" net.roseindia.dao.DataAccessLayerException: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="net.roseindia.dao.EventDao"/>
    	at net.roseindia.main.HibernateFactory.buildIfNeeded(HibernateFactory.java:35) 
    et poutant j'ai mis dans mon fichier de conf hibernate.cfg.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
      <mapping class="net.roseindia.dao.EventDao"/>
    <mapping class="net.roseindia.Event"/>
    si quelqu'un a un peut m'aider ça serais cool
    Merci d'avance

  2. #2
    Membre Expert Avatar de willoi
    Profil pro
    Développeur informatique
    Inscrit en
    Décembre 2006
    Messages
    1 355
    Détails du profil
    Informations personnelles :
    Âge : 52
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Décembre 2006
    Messages : 1 355
    Par défaut
    et tu as bien cree tes classes net.roseindia.dao.EventDao et net.roseindia.Event?

  3. #3
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut
    Citation Envoyé par willoi
    et tu as bien cree tes classes net.roseindia.dao.EventDao et net.roseindia.Event?
    oui j'ai creer mes classe
    net.roseindia.dao.EventDao
    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
     
    package net.roseindia.dao;
     
    import java.util.List;
     
    import net.roseindia.Event;
    public class EventDao extends AbstractDao {
     
        public EventDao() {
            super();
        }
     
     
    .
    ..
    .
     
    }


    net.roseindia.Event
    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
     
    package net.roseindia;
     
    import java.io.Serializable;
     
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
     
    @Entity
    @Table(name = "event")
    public class Event implements Serializable {
    	public Event() {
     
    	}
    	@Id 
    	@Column(name = "id")
    	@GeneratedValue()
    	Integer id;
     
    	@Column(name = "name")
    	String name;
    ..
    mais ça marche pas

  4. #4
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    365
    Détails du profil
    Informations personnelles :
    Localisation : Maroc

    Informations forums :
    Inscription : Janvier 2006
    Messages : 365
    Par défaut
    Bonjour,
    Eh bien, tu dois enlever la déclaration de la classe EventDao dans le fichier de config hibernate, car ce n'est pas une classe persistente, et c'est ce qu'indique l'erreur. Il n'y a pas d'annotation @Entity dans cette classe. Ce qui est normal étant donné le rôle d'un dao, qui est d'encapsuler les méthodes de persistence d'une classe mappée (en l'occurrence ici la classe Event).

  5. #5
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut
    j'e l'ai fait mais ça ne marche toujour pas
    ça donne
    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
     Exception in thread "main" net.roseindia.dao.DataAccessLayerException: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="net.roseindia.Event"/>
    	at net.roseindia.main.HibernateFactory.buildIfNeeded(HibernateFactory.java:35)
    	at net.roseindia.dao.AbstractDao.<init>(AbstractDao.java:17)
    	at net.roseindia.dao.EventDao.<init>(EventDao.java:10)
    	at net.roseindia.main.MainDao.main(MainDao.java:13)
    Caused by: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="net.roseindia.Event"/>
    	at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1600)
    	at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1555)
    	at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1534)
    	at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1508)
    	at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
    	at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
    	at net.roseindia.main.HibernateFactory.configureSessionFactory(HibernateFactory.java:84)
    	at net.roseindia.main.HibernateFactory.buildIfNeeded(HibernateFactory.java:33)
    	... 3 more
    et poutant j'ai mis le mapping pas le fichier hibernate.cfg.xml

  6. #6
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    365
    Détails du profil
    Informations personnelles :
    Localisation : Maroc

    Informations forums :
    Inscription : Janvier 2006
    Messages : 365
    Par défaut
    Montre-nous un peu l'ensemble de ton fichier hibernate.cfg.xml, il se peut qu'on loupe quelque chose dans ta configuration.

  7. #7
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut
    Citation Envoyé par manblaizo
    Montre-nous un peu l'ensemble de ton fichier hibernate.cfg.xml, il se peut qu'on loupe quelque chose dans ta configuration.
    voici le fichier
    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
    <?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">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost/base1</property>
    <property name="connection.username">root</property>
    <property name="connection.password">admin</property>
    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</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">none</property>
     
     
    <mapping class="net.roseindia.Event"/>
    </session-factory>
    </hibernate-configuration>

  8. #8
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    365
    Détails du profil
    Informations personnelles :
    Localisation : Maroc

    Informations forums :
    Inscription : Janvier 2006
    Messages : 365
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    Exception in thread "main" net.roseindia.dao.DataAccessLayerException: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="net.roseindia.Event"/>
    	at net.roseindia.main.HibernateFactory.buildIfNeeded(HibernateFactory.java:35)
    	at net.roseindia.dao.AbstractDao.<init>(AbstractDao.java:17)
    	at net.roseindia.dao.EventDao.<init>(EventDao.java:10)
    	at net.roseindia.main.MainDao.main(MainDao.java:13)
    En principe, rien à dire sur la config. Le problème pourrait venir de ton code dans la classe où tu crées la sessionFactory (vraisemblablement HibernateFactory.buildIfNeeded()). Dans ce code tu fais sûrement :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    sessionFactory = new Configuration().configure().buildSessionFactory();
    Et comme tu utilises maintenant des annotations, il faudrait remplacer ce code par :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    sessionFactory = new AnnotationConfiguration().buildSessionFactory();

  9. #9
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut
    voici ma class ou je me connect


    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
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
     
    public class HibernateUtil {
     
     
     
    	    public static final SessionFactory sessionFactory;
     
    	    static {
    	        try {
    	            // Create the SessionFactory from hibernate.cfg.xml
    	            sessionFactory = new AnnotationConfiguration().configure("hibernate.cfg.xml").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 final ThreadLocal session = new ThreadLocal();
     
    	    public static Session currentSession() throws HibernateException {
    	        Session s = (Session) session.get();
    	        // Open a new Session, if this thread has none yet
    	        if (s == null) {
    	            s = sessionFactory.openSession();
    	            // Store it in the ThreadLocal variable
    	            session.set(s);
    	        }
    	        return s;
    	    }
     
    	    public static void closeSession() throws HibernateException {
    	        Session s = (Session) session.get();
    	        if (s != null)
    	            s.close();
    	        session.set(null);
    	    }
     
    	    static Connection conn; 
    	    static Statement st;
    		public static void setup(String sql) {
    			try {
    				// Step 1: Load the JDBC driver.
    				Class.forName("com.mysql.jdbc.Driver");
    				System.out.println("Driver Loaded.");
    				// Step 2: Establish the connection to the database.
    				String url = "jdbc:mysql://localhost/base1";
     
    				conn = (Connection) DriverManager.getConnection(url, "root", "admin");
    				System.out.println("Got Connection.");
     
    				st = (Statement) conn.createStatement();
    				st.executeUpdate(sql);
    			} catch (Exception e) {
    				System.err.println("Got an exception! ");
    				e.printStackTrace();
    				System.exit(0);
    			}
    		}
    		public static void checkData(String sql) {
    			try {
    				HibernateUtil.outputResultSet((ResultSet) st
    						.executeQuery(sql));
    //				conn.close();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
     
    	    public static void outputResultSet(ResultSet rs) throws Exception{
    			ResultSetMetaData metadata = (ResultSetMetaData) rs.getMetaData();
     
    			int numcols = metadata.getColumnCount();
    			String[] labels = new String[numcols]; 
    			int[] colwidths = new int[numcols];
    			int[] colpos = new int[numcols];
    			int linewidth;
     
    			linewidth = 1;
    			for (int i = 0; i < numcols; i++) {
    				colpos[i] = linewidth; 
    				labels[i] = metadata.getColumnLabel(i + 1); // get its label
    				int size = metadata.getColumnDisplaySize(i + 1);
    				if (size > 30 || size == -1)
    					size = 30;
    				int labelsize = labels[i].length();
    				if (labelsize > size)
    					size = labelsize;
    				colwidths[i] = size + 1; // save the column the size
    				linewidth += colwidths[i] + 2; // increment total size
    			}
     
    			StringBuffer divider = new StringBuffer(linewidth);
    			StringBuffer blankline = new StringBuffer(linewidth);
    			for (int i = 0; i < linewidth; i++) {
    				divider.insert(i, '-');
    				blankline.insert(i, " ");
    			}
    			// Put special marks in the divider line at the column positions
    			for (int i = 0; i < numcols; i++)
    				divider.setCharAt(colpos[i] - 1, '+');
    			divider.setCharAt(linewidth - 1, '+');
     
    			// Begin the table output with a divider line
    			System.out.println(divider);
     
    			// The next line of the table contains the column labels.
    			// Begin with a blank line, and put the column names and column
    			// divider characters "|" into it. overwrite() is defined below.
    			StringBuffer line = new StringBuffer(blankline.toString());
    			line.setCharAt(0, '|');
    			for (int i = 0; i < numcols; i++) {
    				int pos = colpos[i] + 1 + (colwidths[i] - labels[i].length()) / 2;
    				overwrite(line, pos, labels[i]);
    				overwrite(line, colpos[i] + colwidths[i], " |");
    			}
    			System.out.println(line);
    			System.out.println(divider);
     
    			while (rs.next()) {
    				line = new StringBuffer(blankline.toString());
    				line.setCharAt(0, '|');
    				for (int i = 0; i < numcols; i++) {
    					Object value = rs.getObject(i + 1);
    					overwrite(line, colpos[i] + 1, value.toString().trim());
    					overwrite(line, colpos[i] + colwidths[i], " |");
    				}
    				System.out.println(line);
    			}
    			System.out.println(divider);
     
    	    }
     
    		static void overwrite(StringBuffer b, int pos, String s) {
    			int len = s.length();
    			for (int i = 0; i < len; i++)
    				b.setCharAt(pos + i, s.charAt(i));
    		}
     
    	}
    mais la je pense que le probleme vient de la class test car j'ai rajouter
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Session sess = session.getCurrentSession();
    dans ma classe test le message erreur a changer maitement ça me donne
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    5:57:29,843  INFO SettingsFactory:290 - Statistics: disabled
    15:57:29,843  INFO SettingsFactory:294 - Deleted entity synthetic identifier rollback: disabled
    15:57:29,843  INFO SettingsFactory:309 - Default entity-mode: pojo
    15:57:29,843  INFO SettingsFactory:313 - Named query checking : enabled
    15:57:29,906  INFO SessionFactoryImpl:161 - building session factory
    15:57:30,312  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
    Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
    	at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:542)
    	at net.roseindia.main.MainDao.main(MainDao.java:18)
    ma classe test est
    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
     public class MainDao {
    	public static void main(String[] args) {
     
    	    // hibernate code start
    		SessionFactory session = HibernateUtil.sessionFactory;
    		Session sess = session.getCurrentSession();
    		//** Starting the Transaction *//*
    		//Transaction tx = (Transaction) sess.beginTransaction();
    	        EventDao eventDao = new EventDao();
    	        Employee event = new Employee();
    	        event.setName("bibib");
     
    	        eventDao.create(event);
     
     
    }

  10. #10
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    365
    Détails du profil
    Informations personnelles :
    Localisation : Maroc

    Informations forums :
    Inscription : Janvier 2006
    Messages : 365
    Par défaut
    Et ça donne toujours la même erreur ? Bizarre !!
    http://www.hibernate.org/hib_docs/an...html/ch01.html

  11. #11
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    365
    Détails du profil
    Informations personnelles :
    Localisation : Maroc

    Informations forums :
    Inscription : Janvier 2006
    Messages : 365
    Par défaut
    Désolé, je n'avais pas lu ton dernier post en entier. Alors, plutôt que de faire :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Session sess = session.getCurrentSession();
    fais plutot :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Session sess = HibernateUtil.currentSession();
    Et comme tu as configuré
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    <property name="current_session_context_class">thread</property>
    ceci devrait aussi suffire
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Session sess = HibernateUtil.sessionFactory.getCurrentSession();

  12. #12
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut
    J'ai fait ce que tu ma dit mais ça ne marche toujour pas mais ça changer de message d'erreur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    7:18:38,515  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
    Exception in thread "main" java.lang.ClassCastException: org.hibernate.transaction.JDBCTransaction
    	at net.roseindia.main.MainDao.main(MainDao.java:26)
    je ne comprend pas j'ai mis tous les lib
    hibernate3.jar
    hibernate.annatation.jar
    hibernate.validator.jar
    hibernate.commons.annotation.jar

  13. #13
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    365
    Détails du profil
    Informations personnelles :
    Localisation : Maroc

    Informations forums :
    Inscription : Janvier 2006
    Messages : 365
    Par défaut
    Ben là c'est juste un problème de cast. Regarde bien dans ta classe MainDao.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
     public class MainDao {
    	public static void main(String[] args) {
    	  	    
    	    // hibernate code start
    		SessionFactory session = HibernateUtil.sessionFactory;
    		Session sess = session.getCurrentSession();
    		//** Starting the Transaction *//*
    		//Transaction tx = (Transaction) sess.beginTransaction();
    	        EventDao eventDao = new EventDao();
    	        Employee event = new Employee();
    	        event.setName("bibib");
     
    	        eventDao.create(event);	       
    }
    EventDao attend un objet Event, alors que dans ton code ci-dessus tu instancies un objet Employee, bien que tu l'appelle "event".

  14. #14
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut
    no mais je l'ai changer ça fait un moment mais ça change pas lemessage d'erreur

  15. #15
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    365
    Détails du profil
    Informations personnelles :
    Localisation : Maroc

    Informations forums :
    Inscription : Janvier 2006
    Messages : 365
    Par défaut
    Alors, montre-nous les dernières versions des classes MainDao.java et EventDao.java, c'est certainement dans l'une des deux que le problème se pose.

  16. #16
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut
    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
     
    public class MainDao {
    	public static void main(String[] args) throws Exception{
     
    	    // hibernate code start
    		HibernateUtil.sessionFactory.getCurrentSession();
    		//** Starting the Transaction *//*
    		//Transaction tx = (Transaction) sess.beginTransaction();
    	        EventDao eventDao = new EventDao();
    	        Event event = new Event();
    	        event.setName("bibib");
     
    	        eventDao.create(event);
     
    	        //** Commiting the changes *//*
    		//tx.commit();
    		System.out.println("Record Inserted");	
    		//** Closing Session *//*
    		//session.close();
     
    	       // HibernateUtil.checkData("select uid, name from events");
    }
    }

  17. #17
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    365
    Détails du profil
    Informations personnelles :
    Localisation : Maroc

    Informations forums :
    Inscription : Janvier 2006
    Messages : 365
    Par défaut
    On peut voir aussi EventDao ?

  18. #18
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut
    désoler hier on avait un probeleme de reseau voici le code

    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
    public class EventDao extends AbstractDao {
     
        public EventDao() {
            super();
        }
     
        /**
         * Insert a new Event into the database.
         * @param event
         */
        public void create(Event event) throws DataAccessLayerException {
            super.saveOrUpdate(event);
        }
     
     
        /**
         * Delete a detached Event from the database.
         * @param event
         */
        public void delete(Event event) throws DataAccessLayerException {
            super.delete(event);
        }
     
        /**
         * Find an Event by its primary key.
         * @param id
         * @return
         */
        public Event find(Long id) throws DataAccessLayerException {
            return (Event) super.find(Event.class, id);
        }
     
        /**
         * Updates the state of a detached Event.
         *
         * @param event
         */
        public void update(Event event) throws DataAccessLayerException {
            super.saveOrUpdate(event);
        }
     
        /**
         * Finds all Events in the database.
         * @return
         */
        public List findAll() throws DataAccessLayerException{
            return super.findAll(Event.class);
        }
     
    }

  19. #19
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    365
    Détails du profil
    Informations personnelles :
    Localisation : Maroc

    Informations forums :
    Inscription : Janvier 2006
    Messages : 365
    Par défaut
    Bonjour,
    A priori il n'y a rien d'anormal dans ce code de la classe EventDao, mais comme ses méthodes délèguent à la super-classe, montre un peu le code de AbstractDao, et peut-être aussi la trace complète de l'erreur parce que là le problème peut venir de n'importe où dans tes différentes classes.

  20. #20
    Membre averti
    Inscrit en
    Avril 2007
    Messages
    45
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 45
    Par défaut
    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
     public abstract class AbstractDao {
        private Session session;
        private Transaction tx;
     
        public AbstractDao() {
            HibernateFactory.buildIfNeeded();
        }
     
        protected void saveOrUpdate(Object obj) {
            try {
                startOperation();
                session.saveOrUpdate(obj);
                tx.commit();
            } catch (HibernateException e) {
                handleException(e);
            } finally {
                HibernateFactory.close(session);
            }
        }
     
        protected void delete(Object obj) {
            try {
                startOperation();
                session.delete(obj);
                tx.commit();
            } catch (HibernateException e) {
                handleException(e);
            } finally {
                HibernateFactory.close(session);
            }
        }
     
        protected Object find(Class clazz, Long id) {
            Object obj = null;
            try {
                startOperation();
                obj = session.load(clazz, id);
                tx.commit();
            } catch (HibernateException e) {
                handleException(e);
            } finally {
                HibernateFactory.close(session);
            }
            return obj;
        }
     
        protected List findAll(Class clazz) {
            List objects = null;
            try {
                startOperation();
                Query query = session.createQuery("from " + clazz.getName());
                objects = query.list();
                tx.commit();
            } catch (HibernateException e) {
                handleException(e);
            } finally {
                HibernateFactory.close(session);
            }
            return objects;
        }
     
        protected void handleException(HibernateException e) throws DataAccessLayerException {
            HibernateFactory.rollback(tx);
            throw new DataAccessLayerException(e);
        }
     
        protected void startOperation() throws HibernateException {
            session = HibernateFactory.openSession();
            tx = session.beginTransaction();
        }
    HibernateFactory que utilise DAO
    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
     public class HibernateFactory {
        private static SessionFactory sessionFactory;
        private static Log log = LogFactory.getLog(HibernateFactory.class);
     
        /**
         * Constructs a new Singleton SessionFactory
         * @return
         * @throws HibernateException
         */
        public static SessionFactory buildSessionFactory() throws HibernateException {
            if (sessionFactory != null) {
                closeFactory();
            }
            return configureSessionFactory();
        }
     
        /**
         * Builds a SessionFactory, if it hasn't been already.
         */
        public static SessionFactory buildIfNeeded() throws DataAccessLayerException{
            if (sessionFactory != null) {
                return sessionFactory;
            }
            try {
                return configureSessionFactory();
            } catch (HibernateException e) {
                throw new DataAccessLayerException(e);
            }
        }
        public static SessionFactory getSessionFactory() {
            return sessionFactory;
        }
     
     
        public static Session openSession() throws HibernateException {
            buildIfNeeded();
            return sessionFactory.openSession();
        }
     
        public static void closeFactory() {
            if (sessionFactory != null) {
                try {
                    sessionFactory.close();
                } catch (HibernateException ignored) {
                    log.error("SessionFactory n'a pas pu se fermer", ignored);
                }
            }
        }
     
        public static void close(Session session) {
            if (session != null) {
                try {
                    session.close();
                } catch (HibernateException ignored) {
                    log.error("Session n'a pas pu se fermer", ignored);
                }
            }
        }
     
        public static void rollback(Transaction tx) {
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (HibernateException ignored) {
                log.error(" Transaction n'a pas être effectue", ignored);
            }
        }
        /**
         *
         * @return
         * @throws HibernateException
         */
        private static SessionFactory configureSessionFactory() throws HibernateException {
           // Configuration configuration =  new Configuration();
          //  configuration.configure();
            //sessionFactory = configuration.buildSessionFactory();
     
            sessionFactory =  new AnnotationConfiguration().buildSessionFactory();
            return sessionFactory;
        }
    }
    erreur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    17:55:03,000  INFO Version:15 - Hibernate Annotations 3.3.0.GA
    17:55:03,031  INFO Environment:464 - Hibernate 3.0.3
    17:55:03,031  INFO Environment:477 - hibernate.properties not found
    17:55:03,031  INFO Environment:510 - using CGLIB reflection optimizer
    17:55:03,031  INFO Environment:540 - using JDK 1.4 java.sql.Timestamp handling
    Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.util.ReflectHelper.classForName(Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Class;
    	at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:752)
    	at HibernateFactory.configureSessionFactory(HibernateFactory.java:84)
    	at HibernateFactory.buildIfNeeded(HibernateFactory.java:30)
    	at AbstractDao.<init>(AbstractDao.java:14)
    	at EventDao.<init>(EventDao.java:12)
    	at Main.main(Main.java:18)

+ Répondre à la discussion
Cette discussion est résolue.
Page 1 sur 2 12 DernièreDernière

Discussions similaires

  1. Hibernate annotation: class not mapped
    Par Babilion dans le forum Hibernate
    Réponses: 7
    Dernier message: 25/03/2010, 22h54
  2. [hibernate 2.0]Probleme mapping
    Par kekesilo dans le forum Hibernate
    Réponses: 1
    Dernier message: 07/12/2008, 15h29
  3. pb Mapping héritage hibernate annotations
    Par lilou13_13 dans le forum JPA
    Réponses: 1
    Dernier message: 08/07/2007, 22h12
  4. [hibernate] Probleme mapping -> clé composée
    Par zorm dans le forum Hibernate
    Réponses: 3
    Dernier message: 04/07/2007, 12h57
  5. Réponses: 1
    Dernier message: 26/06/2006, 10h21

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