使用Spring Boot,我如何在一个新表上创建两个实体之间的关系,并为其提供额外的列



我有这两个实体:

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

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

将其从"员工"中完全删除,并仅在"合同"中使用。这对我来说是最好的做法。

我找到了实现这一目标的方法:

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

我不知道您为什么要为一对多关系创建一个新表。通常,我们只在存在多对多关系的情况下创建新表。当我们有多对多关系时,我们用复合主键创建了第三个关系表。为什么需要为一对多创建第三个关系表。

最新更新