Using Java Records with JPA

06 May 2023 Balmiki Mandal 0 Core Java

Using Java Records with JPA

Java Records are a new feature in Java 14 that is designed to simplify the definition and use of simple objects. Java Records provide an easy way to define data classes that have an immutable state and lack their own business logic. This makes them ideal candidates for use with the Java Persistence API (JPA). In this article, we'll explore how to use Java Records with JPA.

Defining a Java Record

The first step in using Java Records with JPA is to define a Record class. When defining a Record class, you must follow a few rules:

  • Your class must be declared with the record keyword
  • Your class must have a private, final field for each property
  • Your class must have a public static method named of() that returns an instance of the class
  • Your class must have an accessible constructor that takes parameters for each property
  • Your class must have getter methods for each property, with the name of the getter being the same as the name of the field

For example, here is a Java Record that defines an entity called Person:

record Person(String firstName, String lastName, int age) {

}

Mapping a Java Record to a Database Table

Once you have defined your Java Record, the next step is to map it to a database table. To do this, you will need to use the @Entity annotation in conjunction with the @Table annotation:

@Entity
@Table(name="people")
public record Person(String firstName, String lastName, int age) {

}

The @Entity and @Table annotations tell the JPA provider which table the Java Record should be mapped to. The @Table annotation also allows you to specify additional properties, such as the name of the table, the primary key column(s), and more.

Using Java Records with JPA

Now that the Java Record is mapped to a database table, you can start using it with JPA. To create a new Person object, you can use the static of() method defined in the Person class:

Person p = Person.of("John", "Doe", 30);

To persist a Person object to the database, you can use the EntityManager.persist() method:

entityManager.persist(p);

To query for Person objects from the database, you can use the EntityManager.find() method:

Person p = entityManager.find(Person.class, id);

Conclusion

In this article, we've explored how to use Java Records with JPA. We looked at how to define a Java Record and how to map it to a database table. Finally, we discussed how to use the Java Record with JPA, including creating, persisting, and querying objects.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.