Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Java 16 record with JPA entity?

I am trying to do something similar like below.

@Entity
@Table(name="Sample")
public record Sample(Integer id, String name) {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Integer id;

    @Column(name="username")
    private String name;

}

However, it gives me error "User declared non-static fields id are not permitted in a record" and same for name field as well.

Is there a way to use new java feature "record" with JPA annotation?

like image 242
MongGu Avatar asked Sep 03 '25 04:09

MongGu


1 Answers

tl;dr

No support currently, but some support coming in 2024-2025.

Future

According to Jakarta EE 11: The Next Major Jakarta EE Update Is Shaping Up by Ivar Grimstad, 2023-08:

  • In Jakarta Persistence 3.2, “Java Records will be usable as an embeddable type”.
  • Jakarta Validation 3.1 will add support for Java Records.

Present

See the article, Using Records as Projections in JPA by Billy Korando. The following is a brief summary.

Records cannot be Entities

Jakarta Persistence (JPA; formerly Java Persistence API) implementations such as Hibernate depend on features either forbidden or not recommended by the JEP 395: Records spec: no-arg constructors, non-final fields, setters, etc.

➥ So, no, records cannot be used as JPA Entity.

Other uses of records

You can use records with:

  • CriteriaBuilder
  • TypedQuery
  • NativeQuery
  • Mapping definition

Spring data has some support as well.

See that article linked above for details, and for links to two other articles.

like image 75
Basil Bourque Avatar answered Sep 05 '25 21:09

Basil Bourque