Hibernate: Where do insertable = false, updatable = false belong in composite primary key constellations involving foreign keys?

Let me answer step by step.

1. When do you need ` insertable = false, updatable = false`?

Let’s look at the below mapping,

public class Zip {

    @ManyToOne
    @JoinColumn(name = "country_code", referencedColumnName = "iso_code")
    private Country country = null

    @Column(name = "country_code")
    private String countryCode;

}

Here we are referring to the same column in the table using two different properties. In the below code,

Zip z = new Zip();

z.setCountry(getCountry("US"));
z.setCountryCode("IN");

saveZip(z);

What will Hibernate do here??

To prevent these kind of inconsistency, Hibernate is asking you to specify the update point of relationships. Which means you can refer to the same column in the table n number of times but only one of them can be used to update and all others will be read only.

2. Why is Hibernate complaining about your mapping?

In your Zip class you are referring to the Embedded id class ZipId that again contains the country code. As in the above scenario now you have a possibility of updating the country_code column from two places. Hence the error given by Hibernate is proper.

3. How to fix it in your case?

No. Ideally you want your ZipId class to generate the id, so you should not add insertable = false, updatable = false to the countryCode inside the ZipId. So the fix is as below modify the country mapping in your Zip class as below,

@ManyToOne
@JoinColumn(name = "country_code", referencedColumnName = "iso_code",
insertable =  false, updatable = false)
private Country country;

Hope this helps your understanding.

Leave a Comment