Search code examples
sqlspringjpaannotationsone-to-one

One to one with referencedColumnName mapping on wrong field


I'm facing problem on one to one relationship. I have 2 tables, one Article which has 1 FK "FICHE_ID" refrences to the second table's id Fiche(ID_FICHE) and the problem is that JPA is not mapping on the right field, it's taking ID_ARTICLE to map ID_FICHE instead of FICHE_ID. This is the code below :

@Entity
@Table(name="ARTICLE")
public class Article  implements Serializable{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID_ARTICLE")
Integer id=0;

@Column(name="ENTREPRISE")
private String entreprise;

@Column(name="CODE_ARTICLE")
private String code;

@Column(name="LIBELLE_ARTICLE")
private String libelle;

@Column(name="ROLE_READ")
private String role;

@Column(name="PRIX")
private int prix;

@Column(name="OBLIGATOIRE")
private String obligatoire;

@NaturalId
@Column(name="TAILLE_CODE")
private String tailleCode;

@NaturalId
@Column(name="FICHE_ID")
private Integer ficheId;

@OneToOne(fetch = FetchType.EAGER,mappedBy="article")
FicheArticle fiche;

And

@Entity
@Table(name="FICHE")
public class FicheArticle {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID_FICHE",insertable = false,updatable = false)
private Integer id=0;
@Lob
@Column(name="FICHE",insertable = false,updatable = false)
private byte[] fiche;
@Lob
@Column(name="FICHE")
private Blob ficheBlob;
@Column(name="ENTREPRISE")
private String entreprise;
@OneToOne
@JoinColumn(name="ID_FICHE", referencedColumnName = "FICHE_ID")  
private Article article;

Please, can you help me ?


Solution

  • I am not positive I understand your question; but it looks like a few things need to be changed. Since the foreign key is held by the ARTICLE table, you cannot use mappedBy on the Article.fiche mapping. Instead, you should specify the appropriate join column on Article.fiche and mappedBy on Fiche.article:

    @Entity
    @Table(name = "ARTICLE")
    public class Article  implements Serializable {
    
    private static final long serialVersionUID = 1L;
        
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID_ARTICLE")
    Integer id = 0;
    
    // ...
    
    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "FICHE_ID", referencedColumnName = "ID_FICHE")
    FicheArticle fiche;
    

    And

    @Entity
    @Table(name = "FICHE")
    public class FicheArticle {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID_FICHE", insertable = false, updatable = false)
    private Integer id = 0;
    
    // ...
    
    @OneToOne(mappedBy = "fiche")
    @JoinColumn(name="ID_FICHE", referencedColumnName = "FICHE_ID")  
    private Article article;
    

    Also, I'm guessing Article.ficheId is not a @NaturalId for Article; so you should simply remove the field (and its mapping).