Search code examples
springhibernatejpaormhibernate-mapping

Shared Primary Key between two Entities Not Working


I have created two Entities namely Teacher and Detail, the code snippet is shown below

Teacher.java

@Entity
@Table(name = "teacher")
public class Teacher implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;
    @Column(name = "name")
    private String name;
    @Column(name = "age")
    private int age;

    @OneToOne(mappedBy = "teacher", cascade = CascadeType.ALL)
    private Detail detail;

    public Teacher() {
    }

    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }
//getter and setter
}

Detail.java

@Entity
@Table(name = "detail")
public class Detail implements Serializable {

    @Id
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "id")
    private Teacher teacher;
    @Column(name = "subjects")
    private String subjects;

    public Detail() {
    }

    public Detail(String subjects) {
        this.subjects = subjects;
    }
//getter and setter
}

I am trying to achieve one to one mapping with the shared primary key concept but when i execute the controller, only Teacher table is updating with the value

try {
    Teacher teacher=new Teacher("xyz",23);
    Detail detail=new Detail("Java,c,c++");

    teacher.setDetail(detail);
    session.beginTransaction();
    session.save(teacher);
    session.getTransaction().commit();
    model.addAttribute("added", "data inserted");
    session.close();
}

After executing only Teacher table is updated with the specified values.Detail table is still showing empty


Solution

  • It does not work exactly like that. You still need the id field in your Detail, so add:

    @Id
    private long id;
    

    to your Deatail class.

    And - as comment suggests - replace the @Id annotation in field Teacher to @MapsId. This way the id of Teacher is mapped to the id of Detail BUT ONLY if you also set the teacher to the detail - you always need to set both sides of relationship - like:

    teacher.setDetail(detail);
    detail.setTeacher(teacher);