java - 使用 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
默认为空。
我怎样才能做到这一点?
解决方案
您需要手动创建它
@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 中。这对我来说是最佳实践。
推荐阅读
- magento - 在 Magento 2 中使用 Graphql 的好处
- javascript - window.__REDUX_DEVTOOLS_EXTENSION_COMPOSER__ 在 Electron 应用程序中未定义
- python - OpenCV:为颜色过滤选择 HSV 阈值
- android - 使用 API 28 时不显示 Recyclerview
- pgadmin - pgAdmin 4 在查询生成器上崩溃(在执行查询之前)
- kubernetes - Istio 中的内部服务请求
- ios - 使用 React-Native - 拉动刷新不隐藏在 iOS 上,在 Android 上运行良好
- docker - 如何在 Docker 运行期间运行 shell 脚本
- bash - Bash 脚本 rm 命令在 while 循环中失败
- git - 使用 Git 2.22.1 使用 refs/pull 克隆 GitHub git 存储库(致命:ref 的多个更新)