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

Persistance des données Java Discussion :

Comment gérer les clefs étrangères ?


Sujet :

Persistance des données Java

  1. #1
    Membre très actif
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2009
    Messages
    391
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Avril 2009
    Messages : 391
    Par défaut Comment gérer les clefs étrangères ?
    Bonjour à tous =D,

    j'ai une petite difficulté à comprendre la gestion des clefs étrangères avec Hibernate.

    J'utilise Spring ORM 4 et Hibernate 5. J'ai deux tables MySQL, Utilisateur et Adresse.

    Pour moi, un utilisateur a une adresse et vice versa. Donc c'est une relation 1-1 (corrigez moi si je me trompe) et donc je dois utiliser l'annotation One-to-one.
    J'ai donc un idUtilisateur dans ma classe Adresse qui fait référence à l'id de la table Utilisateur. :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    @OneToOne
    @JoinColumn(name="id")
    public Utilisateur getIdUtilisateur() {
    	return idUtilisateur;
    }
    Pourtant lorsque je lance mon main pour tester j'ai ces erreurs là :

    Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not execute statement
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2921)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3421)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:468)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3135)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2352)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
    at com.ecollection.dao.AdresseDaoImpl.creerAdresse(AdresseDaoImpl.java:30)
    at com.ecollection.service.AdresseServiceImpl.creerAdresse(AdresseServiceImpl.java:26)
    at TestMain.main(TestMain.java:39)
    Caused by: java.sql.SQLException: Field 'idUtilisateur' doesn't have a default value
    En sachant que j'ai ce petit bout de code dans mon main :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    		UtilisateurServiceImpl utilisateurService = new UtilisateurServiceImpl();
     
    		Utilisateur utilisateur = new Utilisateur("Valjeant", "Jean");
     
    		utilisateurService.creerUtilisateur(utilisateur);
     
    		AdresseServiceImpl adresseService = new AdresseServiceImpl();
     
    		Adresse nouvelleAdresse = new Adresse("avenue du champagne", "51100", "reims", "france", utilisateur);
     
    		adresseService.creerAdresse(nouvelleAdresse);
    Avez-vous une idée ?

    Merci d'avance =D

  2. #2
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    Tu peux montrer ta classe utilisateur et ta classe address?

  3. #3
    Membre très actif
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2009
    Messages
    391
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Avril 2009
    Messages : 391
    Par défaut
    Salut,

    bien sûr, je les copies/colles à la suite. Par contre j'ai un petit doute pour le One-to-one, dans ma base de données, Utilisateur ne connait pas l'id de l'adresse. C'est une jointure qui ne permet de connaitre l'adresse que grâce à l'idUtilisateur dans Adresse.

    Utilisateur (pas d'idAdresse ni en base, ni en 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
     
    @Entity
    @Table(name="UTILISATEUR")
    public class Utilisateur {
     
    	public Long id;
     
    	public String nom;
    	public String prenom;
     
    	public Utilisateur() {
    		super();
    	}
     
    	public Utilisateur(String nom, String prenom) {
    		super();
    		this.nom = nom;
    		this.prenom = prenom;
    	}
     
    	@Override
    	public String toString() {
    		return "Utilisateur [id=" + id + ", nom=" + nom + ", prenom=" + prenom  + "]";
    	}
     
    	@Id
    	@Column(name="id")
    	@GeneratedValue(generator="increment")
    	@GenericGenerator(name="increment",strategy="increment")
    	public Long getId() {
    		return id;
    	}
     
    	public void setId(Long id) {
    		this.id = id;
    	}
     
    	public String getNom() {
    		return nom;
    	}
     
    	public void setNom(String nom) {
    		this.nom = nom;
    	}
     
    	public String getPrenom() {
    		return prenom;
    	}
     
    	public void setPrenom(String prenom) {
    		this.prenom = prenom;
    	}
     
    }
    Adresse :

    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
     
    @Entity
    @Table(name="ADRESSE")
    public class Adresse {
     
    	private Long id;
     
    	private String rue;
    	private String codePostal;
    	private String ville;
    	private String pays;
     
    	private Utilisateur idUtilisateur;
     
    	@Override
    	public String toString() {
    		return ""
    				+ "Adresse [rue=" 
    				+ rue 
    				+ ", codePostal=" 
    				+ codePostal 
    				+ ", ville=" 
    				+ ville 
    				+ ", pays=" 
    				+ pays 
    				+ "]";
    	}
     
    	public Adresse() {
    	}
     
    	public Adresse(String rue, String codePostal, String ville, String pays) {
    		super();
    		this.rue = rue;
    		this.codePostal = codePostal;
    		this.ville = ville;
    		this.pays = pays;
    	}
     
    	public Adresse(String rue, String codePostal, String ville, String pays, Utilisateur idUtilisateur) {
    		super();
    		this.rue = rue;
    		this.codePostal = codePostal;
    		this.ville = ville;
    		this.pays = pays;
    		this.idUtilisateur = idUtilisateur;
    	}
     
    	/*
    	 * GETTERS/SETTERS
    	 */
     
    	@Id
    	@Column(name="id")
    	@GeneratedValue(generator="increment")
    	@GenericGenerator(name="increment",strategy="increment")
    	public Long getId() {
    		return id;
    	}
     
    	public void setId(Long id) {
    		this.id = id;
    	}
     
    	/**
             * @return the rue
             */
    	public String getRue() {
    		return rue;
    	}
     
    	/**
             * @param rue the rue to set
             */
    	public void setRue(String rue) {
    		this.rue = rue;
    	}
     
    	/**
             * @return the codePostal
             */
    	public String getCodePostal() {
    		return codePostal;
    	}
     
    	/**
             * @param codePostal the codePostal to set
             */
    	public void setCodePostal(String codePostal) {
    		this.codePostal = codePostal;
    	}
     
    	/**
             * @return the ville
             */
    	public String getVille() {
    		return ville;
    	}
     
    	/**
             * @param ville the ville to set
             */
    	public void setVille(String ville) {
    		this.ville = ville;
    	}
     
    	/**
             * @return the pays
             */
    	public String getPays() {
    		return pays;
    	}
     
    	/**
             * @param pays the pays to set
             */
    	public void setPays(String pays) {
    		this.pays = pays;
    	}
     
    	@OneToOne
    	@JoinColumn(name="id")
    	public Utilisateur getIdUtilisateur() {
    		return idUtilisateur;
    	}
     
    	public void setIdUtilisateur(Utilisateur idUtilisateur) {
    		this.idUtilisateur = idUtilisateur;
    	}
     
    }
    Merci d'avance =D

  4. #4
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    Tes tables ont été créées automatiquement ou manuellement?

  5. #5
    Membre très actif
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2009
    Messages
    391
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Avril 2009
    Messages : 391
    Par défaut
    Manuellement, je n'ai pas fait les requêtes de création, j'ai utilisé l'assistant de phpMyAdmin.

    Peut-être que l'annotation correct est @Embedded ?

  6. #6
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    Tu as un champ "idUtilisateur" dans ta base, mais tu ne l'a pas mappé, du coup, il ne fait pas partie de l'insert. Ce qui aurait du être mappé sur idUtilisateur, tu l'a mappé sur une colonne appelée "id" via le @JoinColumn

Discussions similaires

  1. Réponses: 5
    Dernier message: 25/07/2005, 09h29
  2. Réponses: 2
    Dernier message: 08/07/2005, 10h40
  3. [C#/SQL] Comment gérer les exceptions d'une Procédure stockée ?
    Par thomas_strass dans le forum Accès aux données
    Réponses: 10
    Dernier message: 06/07/2005, 10h40
  4. Comment gérer les valeur Nulles dans une requête ?
    Par sondo dans le forum Bases de données
    Réponses: 3
    Dernier message: 16/03/2005, 11h02
  5. Comment gérer les espaces blancs?
    Par Lambo dans le forum XML/XSL et SOAP
    Réponses: 10
    Dernier message: 16/05/2003, 09h44

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