我使用一个嵌入式H2数据库,在该数据库中,我使用@OneToMany关系将一个实体实例(产品)与其他实体(供应商)的多个实例相关联;当我有特定产品的特定供应商时,这很有用。
但是现在,我想将所有供应商与每个产品关联起来;我不想在供应商表中为每种产品生成不同的供应商记录,相反,我希望在供应商表中仅具有5条记录(5个供应商),这些记录与每个产品相关联,我只想说几句像“所有人”一样,是否可以使用JPA注释来做到这一点?

产品实体

@Entity
public class Product {

    @Id
    private String productCode;

    @OneToMany
    @JoinColumn(name = "supplier_id", referencedColumnName = "productCode")
    private List<Supplier> suppliers;

}



供应商实体

@Entity
public class Supplier {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    private String name;
}

最佳答案

单向@OneToMany关联:

@Entity
public class Product {

    @Id
    // @Column(name = "id") maybe
    // @GeneratedValue maybe
    private String productCode;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) // according to your need
    private List<Supplier> suppliers;

    ...
}


和,


@Entity
public class Supplier {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    ...
}



@ManyToOne关联:

@Entity
public class Product {

    @Id
    // @Column(name = "id") maybe
    // @GeneratedValue maybe
    private String productCode;

    ...
}


和,


@Entity
public class Supplier {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "product_id", foreignKey = @ForeignKey(name = "PRODUCT_ID_FK"))
    private Product product;

    private String name;

    ...
}

07-24 09:52
查看更多