简体   繁体   中英

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?

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

Records cannot be Entities

JPA 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.

Other uses of records

You can use records with:

  • CriteriaBuilder
  • TypedQuery
  • NativeQuery
  • Mapping definition

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