When implementing composite primary keys in Hibernate or other ORMs there are up to three places where to put the insertable = false, updatable = false in composite primary
Let me answer step by step.
Lets 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 relation ships. 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.
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 counry_code
column from two places. Hence error given by hibernate is proper.
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.
You can also solve this problem by using @PrimaryKeyJoinColumn
annotation . The PrimaryKeyJoinColumn annotation specifies a primary key column that is used as a foreign key to join to another table.
The PrimaryKeyJoinColumn annotation is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity. If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.