首页 > 解决方案 > 使用 Spring Boot,如何在新表上创建 2 个实体之间的关系并为其提供额外的列?

问题描述

我有这两个实体:

@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默认为空。

我怎样才能做到这一点?

标签: javaspring-bootentityrelationship

解决方案


您需要手动创建它

@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 中。这对我来说是最佳实践。


推荐阅读