JPA - 一个实体如何引用多对多关系中涉及的另外两个实体?

JPA - How can an entity refer to two other entities involved in a ManyToMany relationship?

我有以下表格:

在我的领域模型中,我有一个 Car 实体:

@Entity
@Data
public class Car {

    @Id
    private Long id;

    @ManyToMany
    @JoinTable(name="CarClassType",
        joinColumns= @JoinColumn(name="carId"),
        inverseJoinColumns = @JoinColumn(name="classTypeId"))
    private List<CarType> carTypes;
    
    private String model;
}

我还有一个 CarClassTypeSaleClassType 个实体。我没有 CarClassType 实体。 CarClassTypeSale class 应该如何引用 CarClassType

@Entity
@Data
public class CarClassTypeSale {

    @Id
    private Long id;

    @ManyToOne // this doesn't work; errors with invalid column name
    private Car car;

    @ManyToOne // this doesn't work; errors with invalid column name
    private ClassType classType;

}

此处的建模不需要 @ManyToMany,因为您可以将 CarClassType 建模为实体。因为 CarClassType table 有一个额外的列 id,你实际上也不能这样建模。如果你想要这个,你将不得不同时使用这两个 FK 作为主键并删除 id 列,无论如何我建议你这样做。

@Entity
@Data
public class Car {

    @Id
    private Long id;

    @OneToMany(mappedBy = "car")
    private Set<CarClassType> carTypes;
    
    private String model;
}
@Entity
@Data
public class CarClassType {

    @EmbeddedId
    private CarClassTypeId id;

    @ManyToOne(fetch = LAZY)
    @JoinColumn(name = "carId", insertable = false, updatable = false)
    private Car car;
    
    @ManyToOne(fetch = LAZY)
    @JoinColumn(name = "classTypeId", insertable = false, updatable = false)
    private CarType classType;

    @OneToMany(mappedBy = "carClassType")
    private Set<CarClassTypeSale> sales = new HashSet<>();
}
@Embeddable
@Data
public class CarClassTypeId {

    @Column(name = "carId")
    private Integer carId;
    
    @Column(name = "classTypeId")
    private Integer classTypeId;
}
@Entity
@Data
public class CarClassTypeSale {

    @Id
    private Long id;

    @ManyToOne
    private CarClassType carClassType;

    private LocalDate soldDate;


}

不确定 CarClassTypeSale 如何适合这张图片。你的图表并没有真正告诉我 class 与其他图表的关系。