Home > Mobile >  How to Map a ManyToOne relationship from 2 sides with shared primary key
How to Map a ManyToOne relationship from 2 sides with shared primary key

Time:05-04

I have 3 tables : Employee, Imputation and Task.

  1. each employee may have many imputations and an imputatino can belong to only one employee at a time ( ManyToOne relationship )
  2. List each task may have multiple imputations and an imputation can only belong to one task at a time (ManyToOne relationship
  3. I want the imputation table to have TASK_ID as its PRIMARY_KEY

here are my 3 entities :

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name="employee")
public class AppUser {

    @Id @GeneratedValue(strategy = IDENTITY)
    private Integer id;
    private String first_name;
    private String last_name;
  @OneToMany(mappedBy="employee")
    private List<Imputation> imputations;
}

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Imputation {
  
    @Id
    private String id; //something needs to be done here to have the id = task_id

    private LocalDate day;
    private Double workload;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name= "employee_id")
    private AppUser employee;
}

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor

public class Task {
    @Id
    @GeneratedValue(strategy = SEQUENCE)
    private Long id;

    private String name;
    private String description;

    @OneToMany(mappedBy = "task")
    private List<Imputation> imputations;

}

this is how i want my table Imputation to look like (as i said, task_id is a PRIMARY KEY AND a FOREIGN KEY ) :

task_id | day | workload |employee_id

CodePudding user response:

Try:

@Entity
public class Imputation {
  
    @Id
    @OneToOne
    @JoinColumn(name= "task_id")
    private Task task;

    private LocalDate day;
    private Double workload;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name= "employee_id")
    private AppUser employee;
}

Or if you want to keep a string property in the entity:

@Entity
public class Imputation {
  
    @Id
    private String id;

    @MapsId
    @OneToOne
    @JoinColumn(name= "task_id")
    private Task task;

    private LocalDate day;
    private Double workload;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name= "employee_id")
    private AppUser employee;
}
  • Related