1

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

  • You can navigate from the parent (customer) to the child (shipping address)
  • The key of the parent is stored in the child table
Dónal
  • 181,534
  • 169
  • 555
  • 808
  • of course it is .. check the mappedBy attribute of the `@OneToOne` annotation (in your example put `@OneToOne(mappedBy = “shippingAddress”` in your Customer class) BTW: you should specify a customer `@Id` field also – Repoker Nov 25 '19 at 14:04
  • @Repoker I only included the elements of the JPA classes that are relevant to my . question – Dónal Nov 25 '19 at 14:23
  • true, but JPA will need an annotated `@Id` field to perform the FK join – Repoker Nov 25 '19 at 14:54
  • You are generating schema with hibernate or with some other way – Nonika Nov 25 '19 at 15:36

1 Answers1

0

Try this:

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

        //...
    }
Repoker
  • 192
  • 2
  • 12