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 :

[Débutant] Hibernate + Foreign key


Sujet :

Hibernate Java

  1. #1
    Membre à l'essai
    Inscrit en
    Décembre 2005
    Messages
    23
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 23
    Points : 13
    Points
    13
    Par défaut [Débutant] Hibernate + Foreign key
    Bonjour,

    J'essai de me mettre à Hibernate depuis peu, j'arrive à faire des insertions dans une table unique mais pas à gérer les une relation clé primaire, clé étrangère.

    Dans ma BDD (MySQL) j'ai 2 tables :
    - t_catogories (id_category clé primaire, name)
    - t_products (id_product clé primaire, name, price, id_category clé étrangère pointant sur la table t_categories)

    Ma BDD est correctement configurée.

    Voila mon fichier de mapping pour l'objet Category :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    <hibernate-mapping>
    	<class name="com.testspring.domain.model.Category" table="t_categories">
    		<cache usage="read-write" />
     
    		<id name="categoryID" column="id_category">
    			<generator class="uuid.hex"></generator>
    		</id>
     
    		<property name="name" column="name" />
     
    	</class>
    </hibernate-mapping>
    Pour mon objet Product :
    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
     
    <hibernate-mapping>
    	<class name="com.testspring.domain.model.Product" table="t_products">
    		<cache usage="read-write" />
     
    		<id name="productID" column="id_product">
    			<generator class="uuid.hex"></generator>
    		</id>
     
    		<property name="name" column="name" />
     
    		<many-to-one name="category" class="com.testspring.domain.model.Category"
    			cascade="none" outer-join="auto" update="true" insert="true"
    			column="category_id" />
     
    		<property name="price" column="price" />
     
    	</class>
    </hibernate-mapping>
    Mon objet Product :
    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
     
    package com.testspring.domain.model;
     
    import java.io.Serializable;
     
    public class Product implements Serializable{
     
    	private static final long serialVersionUID = 4048798961366546485L;
     
    	private String productID;
    	private String name;
    	private String price;
    	private Category category;
     
     
    	public Category getCategory() {
    		return category;
    	}
    	public void setCategory(Category category) {
    		this.category = category;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getPrice() {
    		return price;
    	}
    	public void setPrice(String price) {
    		this.price = price;
    	}
    	public String getProductID() {
    		return productID;
    	}
    	public void setProductID(String productID) {
    		this.productID = productID;
    	}
     
    	 public boolean equals(Object o) {
    	        if (this == o) {
    	            return true;
    	        }
    	        if (!(o instanceof Product)) {
    	            return false;
    	        }
     
    	        final Product product = (Product) o;
     
    	        if (productID != null ? !productID.equals(product.productID) : product.productID != null) {
    	            return false;
    	        }
     
    	        return true;
    	    }
     
    	 public int hashCode() {
    	        return (productID != null ? productID.hashCode() : 0);
    	    }
     
    }

    Ma classe permettant de faire mon insertion :
    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
     
    public class ProductManagerImpl implements ProductManager {
     
    	private final Logger log = Logger.getLogger(ProductManagerImpl.class);
    	private ProductDAO productDAO = null;
    	private CategoryManager categoryManager = null;
     
     
    	public void setCategoryManager(CategoryManager categoryManager) {
    		this.categoryManager = categoryManager;
    	}
     
     
    	public void setProductDAO(ProductDAO productDAO) {
    		this.productDAO = productDAO;
    	}
     
    	public void createProduct(Product product) {
    		log.debug("Creating Product : " + product.getName());
     
    		Category category = categoryManager.findCategory(categoryID);
    		product.setCategory(category);
    		productDAO.saveProduct(product);
     
    	}
    ...
     
    }

    Et là evidemment lorsque j'appelle la méthode createProduct j'ai droit à au beau NullPointerException et sincerement je ne voit pas trop pourquoi...

    Si qqun voit pourquoi...

    Merci d'avance.

  2. #2
    Membre actif Avatar de a.snaps
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    209
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Janvier 2007
    Messages : 209
    Points : 241
    Points
    241
    Par défaut
    Tu pourrais mettre la trace?!
    Mais dans tous les cas, tu fais un faute grave: tu ne peux pas utiliser tes id de ta base dans tes .hashCode() et .equals().
    Regarde le code suivant

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    Category category = session.load(Category.class, someId);
     
    Set<Product> products = category.getProductSet();
     
    products.add(new Product("Produit 1")); // Id == null
    products.add(new Product("Produit 2")); // Id == null aussi et écrase donc le produit ajouté jsute avant
     
     
    // produits ne contient qu'un seul article, le second!
    Alex

  3. #3
    Membre à l'essai
    Inscrit en
    Décembre 2005
    Messages
    23
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 23
    Points : 13
    Points
    13
    Par défaut
    Bonjour voila la trace exacte de l'erreur :

    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
     
    1563 [http-8080-Processor24] WARN  org.apache.struts.action.RequestProcessor  - Unhandled Exception thrown: class java.lang.NullPointerException
    1563 [http-8080-Processor24] ERROR org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/SpringTest].[action]  - "Servlet.service()" pour la servlet action a généré une exception
    java.lang.NullPointerException
    	at com.testspring.web.TestAction.execute(TestAction.java:46)
    	at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:106)
    	at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
    	at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
    	at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
    	at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    	at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:173)
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:78)
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    	at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    	at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    	at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    	at java.lang.Thread.run(Unknown Source)
    Par contre, si je pars du principe qu'un produit ne peut appartenir qu'a une seule catégorie doit t'on forcement utiliser un attribut de collection <Product> dans l'objet Category ?

    Si sur le net il y avait un exemple concret tout simple d'utilisation de clé étrangère avec le code source de ce que je souhaite faire ca m'aiderais bien car l'aide d'hibernate bien qu'elle soit traduite reste pour moi parfois abstraite.

    Si je ne peux utiliser les id de ma base dans mes méthodes hashCode et equals que devrais je utiliser à la place ?

    Merci d'avance pour vos éclairssicements

    Bonne soirée

  4. #4
    Membre à l'essai
    Inscrit en
    Décembre 2005
    Messages
    23
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 23
    Points : 13
    Points
    13
    Par défaut
    Bonjour,


    Bon j'ai relu en partie la doc hibernate ce qui m'a permis d'éclaircir mes idées.

    Ce que je recherche à faire c'est une association bidirectionelle en sachant qu'un produit ne peut appartenir qu'à une seule catégorie (donc pas de table de jointure nécessaire)

    Product.java
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
     
    public class Product implements Serializable{
     
    	private static final long serialVersionUID = 4048798961366546485L;
     
    	private String productID;
    	private String name;
    	private String price;
    	private Category category;
    	...
    Category.java
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
     
    public class Category implements Serializable{
     
    	private static final long serialVersionUID = 4048798961366546485L;
     
    	private String categoryID;
    	private String name;
    	private Set<Product> products = new HashSet<Product>();
    	...
    Product.hbm.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
    19
    20
     
    <hibernate-mapping>
    	<class name="com.testspring.domain.model.Product" table="t_products">
    		<cache usage="read-write" />
     
    		<id name="productID" column="id_product">
    			<generator class="uuid.hex"></generator>
    		</id>
     
    		<property name="name" column="name" />
     
    		<many-to-one name="category" class="com.testspring.domain.model.Category"
    			cascade="none" outer-join="auto" update="true" insert="true"
    			column="category_id" />
     
    		<property name="price" column="price" />
     
    	</class>
     
    </hibernate-mapping>
    Category.hbm.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
    19
    20
    21
     
    <hibernate-mapping>
    	<class name="com.testspring.domain.model.Category" table="t_categories">
    		<cache usage="read-write" />
     
    		<id name="categoryID" column="id_category">
    			<generator class="uuid.hex"></generator>
    		</id>
     
    		<property name="name" column="name" />
     
    		<set name="products" inverse="true" cascade="all-delete-orphan"
    			order-by="name asc">
    			<cache usage="read-write" />
    			<key column="category_id"></key>
    			<one-to-many class="com.testspring.domain.model.Product" />
    		</set>
     
    	</class>
     
    </hibernate-mapping>

    J'ai donc crée un Set de Product dans Category pour pouvoir ensuite récuperer facilement une liste d'article par la méthode getProducts.

    Seulement quand je fais l'insert dans la base de données grâce au code suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    public void createProduct(String categoryID, Product product) {
    		Category category = categoryManager.findCategory(categoryID);
    		product.setCategory(category);
    		category.getProducts().add(product);
    		productDAO.saveProduct(product);
    		categoryManager.updateCategory(category);
    	}
    J'obtiens le message d'erreur suivant comme quoi il n'arrive pas à initialiser la collection :
    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
     
    8390 [http-8080-Processor24] WARN  org.hibernate.util.JDBCExceptionReporter  - SQL Error: 1054, SQLState: 42S22
    8390 [http-8080-Processor24] ERROR org.hibernate.util.JDBCExceptionReporter  - Unknown column 'products0_.category_id' in 'field list'
    8406 [http-8080-Processor24] WARN  org.apache.struts.action.RequestProcessor  - Unhandled Exception thrown: class org.springframework.orm.hibernate3.HibernateJdbcException
    8421 [http-8080-Processor24] ERROR org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/SpringTest].[action]  - "Servlet.service()" pour la servlet action a généré une exception
    org.hibernate.exception.SQLGrammarException: could not initialize a collection: [com.testspring.domain.model.Category.products#402881a2108c74be01108c7534630002]
    	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:65)
    	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    	at org.hibernate.loader.Loader.loadCollection(Loader.java:1926)
    	at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:71)
    	at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:520)
    	at org.hibernate.event.def.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:60)
    	at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1695)
    	at org.hibernate.collection.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:454)
    	at org.hibernate.engine.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:828)
    	at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:229)
    	at org.hibernate.loader.Loader.loadEntity(Loader.java:1785)
    	at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:93)
    	at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:81)
    	at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
    	at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
    	at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
    	at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
    	at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:177)
    	at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:87)
    	at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:891)
    	at org.hibernate.impl.SessionImpl.get(SessionImpl.java:828)
    	at org.hibernate.impl.SessionImpl.get(SessionImpl.java:821)
    	at org.springframework.orm.hibernate3.HibernateTemplate$1.doInHibernate(HibernateTemplate.java:465)
    	at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:367)
    	at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:459)
    	at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:453)
    	at com.testspring.domain.dao.hibernate3.CategoryDAOHibernate.getCategory(CategoryDAOHibernate.java:19)
    	at com.testspring.service.impl.CategoryManagerImpl.findCategory(CategoryManagerImpl.java:41)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    	at java.lang.reflect.Method.invoke(Unknown Source)
    	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:281)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:187)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:154)
    	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:176)
    	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:210)
    	at $Proxy3.findCategory(Unknown Source)
    	at com.testspring.web.TestAction.execute(TestAction.java:47)
    	at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:106)
    	at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
    	at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
    	at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
    	at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    	at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:173)
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:78)
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    	at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    	at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    	at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    	at java.lang.Thread.run(Unknown Source)
    Caused by: java.sql.SQLException: Unknown column 'products0_.category_id' in 'field list'
    	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2926)
    	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1571)
    	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1666)
    	at com.mysql.jdbc.Connection.execSQL(Connection.java:2978)
    	at com.mysql.jdbc.Connection.execSQL(Connection.java:2902)
    	at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:933)
    	at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1027)
    	at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:92)
    	at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139)
    	at org.hibernate.loader.Loader.getResultSet(Loader.java:1669)
    	at org.hibernate.loader.Loader.doQuery(Loader.java:662)
    	at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
    	at org.hibernate.loader.Loader.loadCollection(Loader.java:1919)
    	... 66 more
    Je touche presque au but je suis plus très loin je sens

    Si qqun voit pourquoi...

    Merci d'avance

  5. #5
    Inactif  
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    2 189
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : Suisse

    Informations forums :
    Inscription : Mai 2006
    Messages : 2 189
    Points : 2 336
    Points
    2 336
    Par défaut
    bidirectionelle sans table de jointure c est à la limitte de la cohérance pour moi

  6. #6
    Membre habitué Avatar de xv-mnt
    Profil pro
    Inscrit en
    Juillet 2005
    Messages
    142
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Juillet 2005
    Messages : 142
    Points : 178
    Points
    178
    Par défaut
    Dans ton cas, tu n'as pas besoin de table de jointure car tu es dans une relation 1-n car un produit ne peut appartenir qu'à une seule catégorie. Il suffit de mettre dans la table du produit une FK sur la PK de la catégorie.
    Au niveau du mapping :
    1- il faut une ManyToOne de produit vers catégorie avec un attribut de type Categorie, et comme tu veux une relation bi-directionnelle, il faut une OneToMany de Catégorie vers produit avec un attribut de type List<Produit>, en indiquant que le lien est mappé dans Produit.
    En JDK 1.5, çà donnerait :

    classe Categorie
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    @OneToMany(mappedBy="categorie")
    private List<Produit> produits;
    classe Produit
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    @ManyToOne()
    @JoinColumn(name = "ID_CATEGORIE")
    private Categorie  categorie;
    Penser à renseigner les 2 attributs lorsqu'on attache un produit à une categorie.
    Tout le monde savait que c'était impossible à faire. Puis un jour quelqu'un est arrivé qui ne le savait pas, et il le fit (Winston Churchill)

  7. #7
    Membre à l'essai
    Inscrit en
    Décembre 2005
    Messages
    23
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 23
    Points : 13
    Points
    13
    Par défaut
    Il suffit de mettre dans la table du produit une FK sur la PK de la catégorie.
    Normalement c'est bon :

    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
     
    CREATE TABLE `t_categories` (
      `id_category` varchar(32) NOT NULL,
      `name` varchar(50) default NULL,
      PRIMARY KEY  (`id_category`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
     
    CREATE TABLE `t_products` (
      `id_product` varchar(32) default NULL,
      `name` varchar(50) default NULL,
      `id_category` varchar(32) default NULL,
      `price` int(5) default NULL,
      KEY `FK_t_products` (`id_category`),
      CONSTRAINT `FK_t_products` FOREIGN KEY (`id_category`) REFERENCES `t_categories` (`id_category`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    1- il faut une ManyToOne de produit vers catégorie avec un attribut de type Categorie, et comme tu veux une relation bi-directionnelle, il faut une OneToMany de Catégorie vers produit avec un attribut de type List<Produit>, en indiquant que le lien est mappé dans Produit.
    Normalement c'est bon aussi (voir plus haut) j'ai inclus un Set dans mon objet Category et j'ai fait mon association bidirectionelle <many-to-one> et <one-to-many>.

    J'obtiens toujours mon erreur d'initialisation de ma collection...

Discussions similaires

  1. Debutant hibernate foreign key
    Par haskouse dans le forum Hibernate
    Réponses: 3
    Dernier message: 19/08/2009, 13h59
  2. foreign-key sur plusieurs colonnes (Hibernate 3)
    Par ep31 dans le forum Hibernate
    Réponses: 1
    Dernier message: 27/10/2008, 15h00
  3. Problème foreign key avec hibernate
    Par souhait dans le forum Hibernate
    Réponses: 5
    Dernier message: 05/09/2008, 15h23
  4. [Débutant] au risque d'être ridicule + foreign Key
    Par MaitrePylos dans le forum Langage SQL
    Réponses: 9
    Dernier message: 30/06/2005, 16h07
  5. [débutant] Aide pour mettre une FOREIGN KEY sur une table
    Par cauldron dans le forum Langage SQL
    Réponses: 2
    Dernier message: 14/11/2004, 17h16

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