Having a JPA entity (e.g. CompanyAddress) with a somewhat strange primary key setup, where the primary key is also just a foreign key for another table (e.g. Company) with the naive setup of the ID field:

@Id
@ManyToOne()
@JoinColumn(name = "COMPANY_ID")
private Company company;

and then creating a Spring Repository for the entity, I got the error message:

This class [class hu.bmiklos.CompanyAddress] does not define an IdClass

Apparently JPA (or Spring Data, or whatever does the actual magic in the background) thinks that because the class that is used to represent the primary key is not a wrapped primitive, it must be a composite primary key, and thus requires the IdClass annotation for the entity. But declaring an IdClass doesn’t satisfy this requirement, as the underlying field is not a composite key, but the ID of the mapped entity.

The workaround which solved this for me is to declare the ID field twice in the entity, once as the primary key, and once as the foreign key mapped parent entity. (To avoid problems from inconsistent data, JPA requires that both of them can’t be changed in the database though.)

@Id
@Column(name="COMPANY_ID")
private Long companyId;

@ManyToOne()
@JoinColumn(name = "COMPANY_ID", insertable = false, updatable = false)
private Company company;

Leave a Reply

Your email address will not be published. Required fields are marked *