是否可以将@JoinColumn从一个FK引用到JPA / hibernate中另一个FK中的另一列?

时间:2015-12-04 02:25:19

标签: java spring hibernate jpa spring-boot

我想这些问题似乎令人困惑。

广告资源实体

@Entity
@IdClass(InventoryPK.class)
public class Inventory {

    @Id
    @ManyToOne(optional = false)
    @JoinColumn(name = "product_id",
                referencedColumnName = "product_id")
    private Product product;

    @Id
    @ManyToOne(optional = false)
    @JoinColumn(name = "store_id", 
                referencedColumnName = "store_id")
    private Store store;    

    @Column()
    private int stock;

    @Column(precision = 2)
    private double price;
}

订单实体

@Entity
public class SalesOrder {

    @Id
    @Column(name = "order_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "customer_id", 
                referencedColumnName = "customer_id")
    private Customer customer;

    @ManyToOne(optional = false)
    @JoinColumn(name = "store_id", 
                referencedColumnName = "store_id")
    private Store store;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "order_date")
    private Date orderDate;

    @OneToMany(mappedBy = "order")
    private List<OrderDetails> details;
}

订单明细实体

@Entity
@IdClass(OrderDetailsPK.class)
public class OrderDetails {

    @Id
    @ManyToOne(optional = false)
    @JoinColumn(name = "order_id", 
                referencedColumnName = "order_id")
    private SalesOrder order;

    @Id
    @ManyToOne(optional = false)
    @JoinColumns({
        @JoinColumn(name="product_id", 
                    referencedColumnName="product_id"),
        @JoinColumn(name="store_id", 
                    referencedColumnName="store_id"),
    })
    private Inventory inventory;

    @Column()
    private int quantity;
}

这些实体将生成下表

订单实体

order_id  |  customer_id   |  store_id   |  order_date
======================================================

订单明细实体

order_id  |  product_id   |  store_id   |  quantity
======================================================

我可以将store_id中的OrderDetailsstore_id中的SalesOrder相关联,这样我就不需要在OrderDetails中指定它了吗?我的意思是表格应该如下所示。

订单实体

order_id  |  customer_id   |  store_id   |  order_date
======================================================

订单明细实体

order_id  |  product_id   |  quantity
=====================================

为什么呢?我认为我不需要在store_id中指定OrderDetails,因为该信息已在SalesOrder中。要获得Store,我可以OrderDetails#Order#Store。但是,目前我需要指定store_id,因为它是Inventory中的PK。我可以将store_id的{​​{1}}与Inventory的<{1}}相关联吗?

1 个答案:

答案 0 :(得分:0)

是的......那就是我们所说的ManyToMany关系。 使用@ManyToMany注释来实现这一目标...... 示例: - http://www.java2s.com/Tutorial/Java/0355__JPA/ManyToManyJoinTableJoinInverseJoinColumn.htm