Javax-Persistance : Entity does not have a primary key using Java records

680 Views Asked by At

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?

3

There are 3 best solutions below

0
gkatiforis On BEST ANSWER

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
1
Vaibhav Gupta On

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/

0
Pushpendra Kushvaha On

Entity class internally use setter methods to set the data. As record are immutable. It only contain

  • fields
  • all-args constructor
  • getters
  • toString
  • equals/hashCode methods

and not setter methods. So we can't use record as entities.