繁体   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