Composite primary key and ManyToOne hibernate

Viewed 46

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.

2 Answers

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.

Question really is, which entity should be the owner of the relationship? would you like to map bidirectional or single way?

Here is the bidirectional example

@OneToMany(
      fetch = FetchType.EAGER,
      mappedBy = "department",
      orphanRemoval = true,
      cascade = CascadeType.ALL)
private List<Worker> workers;


@JoinColumn(name = "department_id", nullable = false)
@ManyToOne(targetEntity = Department.class, fetch = FetchType.LAZY)
private Department department;

fetch types are optional and depend on the use case

Related