Issue
I'm learning Hibernate and I'm trying to make the Mapping work. My entities are as follows
Department:
@Entity
public class Department {
@Id
@GeneratedValue
private Integer id;
private String name;
private String hqLocation;
// getters and setters omitted for brevity
}
WorkerId:
@Embeddable
public class WorkerId implements Serializable {
private Integer workerId;
private Integer deptId;
// getters and setters omitted for brevity
}
Worker:
@Entity
public class Worker {
@EmbeddedId
private WorkerId id;
private String name;
private Integer age;
// How to make @ManyToOne mapping work?
private Department department;
// getters and setters omitted for brevity
}
Question: How to make @ManyToOne
on the field private Department department;
work? Simply adding the annotation results private Department department;
as null
.
Solution
I think you want to use a "derived identity"; so you should make Worker.department
like this:
@Entity
public class Worker {
@EmbeddedId
private WorkerId id;
private String name;
private Integer age;
@MapsId("deptId")
@ManyToOne // <<<< edit
private Department department;
// getters and setters omitted for brevity
}
Derived identities are discussed (with examples) in the JPA 2.2 spec in section 2.4.1.
Answered By - Brian Vosburgh
Answer Checked By - Pedro (JavaFixing Volunteer)