简体   繁体   中英

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

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?

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM