首页 > 解决方案 > Specifying the owner of a unidirectional @OneToOne JPA mapping

问题描述

I've a one-to-one relationship between Customer and ShippingAddress. I want to ensure that if a Customer is deleted, the ShippingAddress is also deleted, and therefore I want to store the key of customer in the shipping_address table. I only need to navigate from the customer to the address, i.e. the relationship doesn't need to be bidirectional.

According to this JPA guide, the relationship should be mapped like this:

@Entity
public class Customer{

    @OneToOne
    private ShippingAddress shippingAddress;
}

However, this will cause the key of shipping_address to be stored in customer. My objection to this is that it would allow someone to insert a row into shipping_address without associating it with a customer. Similarly, it would allow someone to delate a row in customer without also deleting the associated address.

Is it possible to create a unidirectional one-to-one mapping wherein

标签: javahibernatejpa

解决方案


尝试这个:

    @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;

        //...
    }

推荐阅读