使用 Spring Boot,如何在新的 table 上创建 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;
}

一个工作区可以有很多员工。我需要将关系存储在一个新的 table 中(我们称之为 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
}

然后根据您的要求

The field startDate must be obtained from the Employee, but the endDate will be empty by default.

您可以在持久化那些合约实体时手动处理它

完全从Employee中移除,只在Contract中。这对我来说是最佳实践。

我不确定您为什么要为一对多关系创建一个新的 table。通常我们只在存在多对多关系的地方创建新的table。当我们有多对多关系时,我们创建了第三个关系 table 与复合主键。为什么你需要为一对多创建第三个关系 table .

我找到方法了:

@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;
}