簡體   English   中英

使用 Spring 引導,如何在新表上創建 2 個實體之間的關系並為其提供額外的列?

[英]Using Spring Boot, how can I create the relationship between 2 entities on a new table and give it extra columns?

我有這兩個實體:

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "Workplace")
public class Employee {

    @Id
    @GeneratedValue
    int id;

    String name;

    String dni;

    java.time.LocalDate startDate;

}

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

    @Id
    @GeneratedValue
    int id;

    String code;

    String location;
}

一個工作區可以有許多員工。 我需要將關系存儲在一個新表中(我們稱之為Contract ),並且我需要它具有以下字段:


    int idEmployee;
    
    int idWorkplace;

    java.time.LocalDate startDate;
    
    java.time.LocalDate endDate;

startDate字段必須從 Employee 中獲取,但endDate默認為空。

我怎樣才能做到這一點?

您需要手動創建它

@IdClass(ContractId.class)
@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "Contract")
public class Contract {

     @Id
     private int idEmployee;
     @Id
     private int idWorkplace;

     private java.time.LocalDate startDate;

     private java.time.LocalDate endDate;

     @OneToOne
     Employee employee

}

然后你還需要那個復合鍵

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ContractId implements Serializable {

     private int idEmployee;
     private int idWorkplace;

  }

然后你的相關類需要對這些關系進行一些額外的修改

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

    @Id
    @GeneratedValue
    int id;

    String code;

    String location;

    @OneToMany(mappedBy = "idWorkplace")
    private List<Contract> contracts;
}

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "Workplace")
public class Employee {

    @Id
    @GeneratedValue
    int id;

    String name;

    String dni;

    java.time.LocalDate startDate;

    @OneToOne(mappedBy = "idEmployee")
    Contract contract
}

然后根據您的要求

startDate 字段必須從 Employee 中獲取,但 endDate 默認為空。

您可以在保留這些合同實體時手動處理它

或者

將其從 Employee 中完全刪除,並僅在 Contract 中。 這對我來說是最佳實踐。

我找到了這樣做的方法:

@Getter
@Setter
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class MyOtherTable {
    @Id
    @GeneratedValue
    private Integer id;
    @OneToOne
    private Workplace workplace;
    @OneToOne
    private Employee employee;
    private String otherProperty;
}

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "Employee")
public class Employee {
    @Id
    @GeneratedValue
    private int id;    
    private String name;
    private String dni;
    private java.time.LocalDate startDate;

    @OneToOne                   
    private WorkPlace workplace;
}

我不確定您為什么要為一對多關系創建一個新表。 通常我們只在存在多對多關系的情況下創建新表。 當我們有多對多關系時,我們創建了具有復合主鍵的第三個關系表。 為什么需要為一對多創建第三個關系表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM