Warm tip: This article is reproduced from stackoverflow.com, please click
hibernate hibernate-mapping java one-to-one

Using same entity twice in another entity in hibernate

发布于 2020-03-27 10:20:34

Let us say a class/entity named student which contains an id, father's occupation and mother's occupation and the entity classes are like this

Student class

@Entity
@Table(name = "student")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true, updatable = false)
    private int id;

    @OneToOne
    @JoinColumn(name = "occupationId")
    Occupation fathersOccupation;

    @OneToOne
    @JoinColumn(name = "occupationId")
    Occupation mothersOccupation;

}

and the Occupation class

@Entity
@Table(name = "occupation")
public class Occupation {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "occupationId")
    int occupationId;

    @Column
    String title;

}

When I tried @OneToOne mapping for both father's occupation and mother's occupation it is throwing exception,Repeated column in mapping for entity. I tried adding @Column(name="<columnName>"), but it is not allowed. I really want those two fields,fathersOccupation and mothersOccupation with oneToOne mapping in the student table.

Questioner
Sony
Viewed
33
Abass A 2017-06-16 04:08

@JoinColumn specify the name of the FK Column in your entity.

Your student entity have 2 FKs toward occupation, one for fathersOccupation and another one for mothersOccupation and you define mapping twice for the same. Ideally you should have fathers_occupation_id and mothers_occupation_id field in your student table and same attributes in your entity.

So you should put for each one the corresponding column name in your student table.

@JoinColumn(name ="fathers_occupation_id")
Occupation fathersOccupation;

@JoinColumn(name="mothers_occupation_id")
Occupation mothersOccupation;