I am trying to create a entity class using Java record, but I get the error message "Entity does not have primary key" although I assigned an ID annotation.
import javax.persistence.*;
import java.time.LocalDate;
@Entity
public record Agent (
@Id
String code,
String name,
LocalDate date,
String workingArea,
String country,
String phoneNumber,
boolean licenseToKill,
int credits,
byte[] picture)
{}
What's wrong with this?
CodePudding user response:
A record
cannot be used as Hibernate entity because it breaks the requirements of an entity according to JPA specification. Make it class
and use @Immutable
annotation instead:
@Entity
@Immutable
public class Agent
CodePudding user response:
Just clearing the answer for completeness (although @Turning85 and @gkatiforis have already provided correct explanation):
According to the JPA specification, an entity must follow these requirements:
- the entity class needs to be non-final,
- the entity class needs to have a no-arg constructor that is either public or protected,
- the entity attributes must be non-final.
However, as explained by this article, the Java Record type is defined like this:
- the associated Java class is final,
- there is only one constructor that takes all attributes,
- the Java record attributes are final.
But records are a good fit for a DTO projection, which is often used as a read-only representation of the data stored in your database. more info - https://thorben-janssen.com/java-records-hibernate-jpa/