簡體   English   中英

指定單向 @OneToOne JPA 映射的所有者

[英]Specifying the owner of a unidirectional @OneToOne JPA mapping

我在CustomerShippingAddress之間建立了一對一的關系。 我想確保如果刪除了CustomerShippingAddress也被刪除,因此我想將customer的鍵存儲在shipping_address表中。 我只需要從客戶導航到地址,即關系不需要是雙向的。

根據這個 JPA 指南,關系應該像這樣映射:

@Entity
public class Customer{

    @OneToOne
    private ShippingAddress shippingAddress;
}

但是,這將導致shipping_address的鍵存儲在customer 我對此的反對意見是,它會允許某人將一行插入到shipping_address而無需將其與customer相關聯。 同樣,它允許某人在不刪除相關地址的情況下延遲customer的一行。

是否可以創建單向一對一映射,其中

  • 您可以從父(客戶)導航到子(送貨地址)
  • 父表的鍵存儲在子表中

嘗試這個:

    @Entity
    public class Customer {
        @Id    
        private long id;

        @OneToOne(mappedBy="customer")
        private ShippingAddress shippingAddress;

        //...
    }

    @Entity
    public class ShippingAddress {
        @Id    
        private long id;

        @OneToOne
        @JoinColumn(name = "customer_id", referencedColumnName = "id")
        private Customer customer;

        //...
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM