javax.persistence @JoinColumn无法正常工作

whlutmcx  于 2022-12-17  发布在  Java
关注(0)|答案(1)|浏览(148)

我正在尝试联接2个表(ManytoMany),但遇到以下错误:
导致错误:org. hib.引用com.MD.Medicine.Models.计划的com.MD.Medicine.Models.Meds.assignedMeds的referencedColumnNames(计划日期、计划Id、工作日)未Map到单个属性
我的实体,Plans.java:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "plans")
@EqualsAndHashCode(exclude = "assignedMeds")
public class Plans {
    @EmbeddedId
    private PlansPKId plansPKId;

    @Column
    private String planName;

    @Column
    private String weekday;

    @ManyToMany
    @JoinTable(name = "Plan_Meds", joinColumns = {
            @JoinColumn(name = "planDate", referencedColumnName = "planDate"),
            @JoinColumn(name = "planId", referencedColumnName = "planId"),
            @JoinColumn(name = "weekday", referencedColumnName = "weekday"), }, inverseJoinColumns = @JoinColumn(name = "id"))
    private Set<Meds> assignedMeds = new HashSet<>();

}

PlansPKId.java (for计划模型):

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Embeddable
public class PlansPKId implements Serializable {

    private Date planDate; // format: yyyy-mm-dd
    private long planId;

  

}

Meds.java:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "meds")

public class Meds {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column
    private String name;

    @Column
    private BigDecimal price;

    @Column
    private String category;

    @Column
    private int pillNumber;

    @Column
    private Date date;

    @JsonIgnore
    @ManyToMany(mappedBy = "assignedMeds")
    private Set<Plans> plans = new HashSet<>();

}

当我只加入这个:

@ManyToMany
    @JoinTable(name = "Plan_Meds", joinColumns = {
            @JoinColumn(name = "planDate", referencedColumnName = "planDate"),
            @JoinColumn(name = "planId", referencedColumnName = "planId"), }, 
            inverseJoinColumns = @JoinColumn(name = "id"))
    private Set<Meds> assignedMeds = new HashSet<>();

它工作正常,但是如果我有“工作日”一栏,我就开始得到错误。我不应该这样加入他们吗?

qacovj5a

qacovj5a1#

是的,基本上,@JoinTable的目的是创建 * 一个中间表 *,该表包含每个参与者表的键。

@ManyToMany
    @JoinTable(name = "Plan_Meds", joinColumns = {
            @JoinColumn(name = "planDate", referencedColumnName = "planDate"),
            @JoinColumn(name = "planId", referencedColumnName = "planId"),
            @JoinColumn(name = "weekday", referencedColumnName = "weekday"), }, inverseJoinColumns = @JoinColumn(name = "id"))
    private Set<Meds> assignedMeds = new HashSet<>();

在这种情况下,

joinColumns = {
            @JoinColumn(name = "planDate", referencedColumnName = "planDate"),
            @JoinColumn(name = "planId", referencedColumnName = "planId")}

将引用Plans实体的键plansPKId,并且

inverseJoinColumns = @JoinColumn(name = "id")

将引用Meds实体的键id。由于weekday@JoinColumn(name = "weekday", referencedColumnName = "weekday"),它未引用任何键,因此不应在此处。
如果您需要在连接表中添加更多字段,请手动创建您自己的连接表并使用@ManyToOne:多托马尼

相关问题