Skip to content

JPA (Jakarta Persistence)

JPA recipes: java.time mappings, sequence generators, runtime persistence properties, bulk updates, JSON columns and inheritance.

8 min readUpdated

Jakarta Persistence (formerly JPA, the Java Persistence API) maps Java objects to relational tables. This note collects recipes that come up repeatedly in Jakarta EE applications: type mappings, ID generation, overriding connection settings, Criteria API updates and joins, JSON columns, map collections and the four inheritance strategies.

Package names: Jakarta EE 9 and later use jakarta.persistence.*; Java EE and JPA 2.x use javax.persistence.*. The examples work with either once the imports match.

Map java.time types

JPA 2.2 added the first five java.time types below to the specification. The others depend on the provider; the JDBC types shown are typical defaults.

Java type JDBC type Standard since
java.time.LocalDate DATE JPA 2.2
java.time.LocalTime TIME JPA 2.2
java.time.LocalDateTime TIMESTAMP JPA 2.2
java.time.OffsetTime TIME_WITH_TIMEZONE JPA 2.2
java.time.OffsetDateTime TIMESTAMP_WITH_TIMEZONE JPA 2.2
java.time.Instant TIMESTAMP Jakarta Persistence 3.2
java.time.Duration BIGINT Provider-specific (Hibernate 5)
java.time.ZonedDateTime TIMESTAMP Provider-specific, zone not stored

Generate IDs from a sequence

Use @SequenceGenerator to take primary keys from a database sequence, here starting at 10000001.

@Entity
public class Project implements Serializable {
@Id
@GeneratedValue(generator = "seq_project_id", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "seq_project_id", sequenceName = "seq_project_id", allocationSize = 1, initialValue = 10000001)
private Long id;
// other fields, getters, setters
}
  • name is the generator’s name inside JPA; sequenceName is the sequence in the database.
  • allocationSize = 1 fetches one value per insert. The default is 50, which lets the provider hand out IDs from memory but requires the database sequence to increment by the same amount.

Override persistence unit properties at runtime

Keep persistence.xml as it is and pass a map of properties to override when the EntityManagerFactory is created, for example to point the same unit at another database.

Map<String, String> properties = new HashMap<>();
properties.put("jakarta.persistence.jdbc.url", "<url>");
properties.put("jakarta.persistence.jdbc.user", "<username>");
properties.put("jakarta.persistence.jdbc.password", "<password>");
properties.put("jakarta.persistence.jdbc.driver", "<driver>");
EntityManagerFactory managerFactory = Persistence.createEntityManagerFactory("<persistence unit name>", properties);
EntityManager manager = managerFactory.createEntityManager();

On JPA 2.x (Java EE) the keys start with javax.persistence.jdbc. instead.

Note: Persistence.createEntityManagerFactory() is for unmanaged (Java SE) environments. In a Jakarta EE server the container creates the factory from persistence.xml and you inject it with @PersistenceContext or @PersistenceUnit.

Bulk update with CriteriaUpdate

CriteriaUpdate runs a single UPDATE statement instead of loading and saving each entity. This example recalculates local prices of all products from their prices in foreign currency multiplied by each currency’s exchange rate (rateTCMB, the Central Bank of the Republic of Türkiye rate).

public int bulkUpdatePricesInLocal() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaUpdate<ProductEntity> cu = cb.createCriteriaUpdate(ProductEntity.class);
Root<ProductEntity> root = cu.from(ProductEntity.class);
Join<ProductEntity, CurrencyEntity> currencyToConsumer = root.join(ProductEntity_.currencyToConsumer);
Join<ProductEntity, CurrencyEntity> currencyToRetailer = root.join(ProductEntity_.currencyToRetailer);
Expression<BigDecimal> prodConsumer = cb.prod(root.get(ProductEntity_.priceToConsumer), currencyToConsumer.get(CurrencyEntity_.rateTCMB));
Expression<BigDecimal> prodRetailer = cb.prod(root.get(ProductEntity_.priceToRetailer), currencyToRetailer.get(CurrencyEntity_.rateTCMB));
cu.set(root.get(ProductEntity_.priceToConsumerInLocal), prodConsumer);
cu.set(root.get(ProductEntity_.priceToRetailerInLocal), prodRetailer);
return em.createQuery(cu).executeUpdate();
}
  • ProductEntity_ and CurrencyEntity_ are the static metamodel classes generated by the provider’s annotation processor.
  • executeUpdate() returns the number of updated rows and must run inside a transaction.
  • Bulk updates bypass the persistence context: entities already loaded keep their old values until refreshed.

Note: Joins in a bulk update are not portable. The specification gives an update a single root, and Hibernate rejects joins in bulk statements. If your provider refuses the query, compute the value with a subquery instead.

Many-to-many with extra columns

A plain @ManyToMany join table cannot hold extra data. To store, for example, the task a developer has on a project, map the join table as its own entity with a composite key. @MapsId fills each part of the key from the corresponding relationship.

@Embeddable
public class DeveloperProjectId implements Serializable {
private Long developerId;
private Long projectId;
// constructor, getters, setters, equals, hashCode
}
@Entity
public class DeveloperProject implements Serializable {
@EmbeddedId
private DeveloperProjectId developerProjectId;
@ManyToOne
@MapsId("developerId")
private Developer developer;
@ManyToOne
@MapsId("projectId")
private Project project;
@Column
private String task;
// constructor, getters, setters
}
@Entity
public class Developer implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "developer")
private List<DeveloperProject> projects;
// constructor, getters, setters
}
@Entity
public class Project implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column
private String name;
@OneToMany(mappedBy = "project")
private List<DeveloperProject> developers;
// constructor, getters, setters
}

An embeddable used as an ID must implement equals() and hashCode().

Join with an extra condition in CriteriaBuilder

Join.on() (JPA 2.1) adds a condition to the join itself rather than to the WHERE clause. This matters for left joins: rows of A without a matching B are still returned.

CriteriaQuery<A> searchQuery = criteriaBuilder.createQuery(A.class);
Root<A> aRoot = searchQuery.from(A.class);
Join<A, B> bJoin = aRoot.join("mappedB", JoinType.LEFT);
bJoin.on(criteriaBuilder.equal(bJoin.get("idLanguage"), 22));

The generated SQL is equivalent to:

LEFT OUTER JOIN B ON A.ID = B.A_ID AND B.idLanguage = 22

Store an object as JSON

An AttributeConverter can serialize a value object to a JSON string column with JSON-B (jakarta.json.bind). Start with a plain serializable class:

public class MyJson implements Serializable {
private String stringProp;
private Long longProp;
public String getStringProp() {
return stringProp;
}
public void setStringProp(String stringProp) {
this.stringProp = stringProp;
}
public Long getLongProp() {
return longProp;
}
public void setLongProp(Long longProp) {
this.longProp = longProp;
}
}

The converter writes the object as JSON and reads it back into the same type:

@Converter(autoApply = true)
public class MyJsonConverter implements AttributeConverter<MyJson, String> {
private final JsonbConfig cfg = new JsonbConfig().withFormatting(true);
private final Jsonb jsonb = JsonbBuilder.create(cfg);
@Override
public String convertToDatabaseColumn(MyJson object) {
if (object == null) {
return null;
}
return jsonb.toJson(object);
}
@Override
public MyJson convertToEntityAttribute(String value) {
if (value == null) {
return null;
}
return jsonb.fromJson(value, MyJson.class);
}
}

Use it on the entity field:

@Entity
public class TestEntity implements Serializable {
// other fields
@Column(columnDefinition = "JSON")
@Convert(converter = MyJsonConverter.class)
private MyJson jsonData;
}

With autoApply = true every MyJson attribute is converted automatically, so the @Convert annotation is optional; it documents the intent.

Note: JSON is the MySQL and MariaDB column type. On PostgreSQL use json or jsonb; since the converter binds a string, the JDBC driver needs stringtype=unspecified in the connection URL or the insert fails with a type mismatch.

EclipseLink’s change tracking may treat a converted attribute as immutable. If you modify the object in place (add to a list inside it, change a field) instead of assigning a new instance, no change is detected and no UPDATE is issued. Annotate such fields with EclipseLink’s @Mutable so the provider compares their value on commit.

@Column(columnDefinition = "JSON")
@Convert(converter = RehearsalAttributeConverter.class)
@Mutable
private Rehearsal rehearsal;

The value class and its converter follow the same pattern as above:

public class Rehearsal implements Serializable {
private List<Product> products;
private Map<Product, Feature> features;
private double shortTermDebt = 0;
// getters, setters
}
@Converter(autoApply = true)
public class RehearsalAttributeConverter implements AttributeConverter<Rehearsal, String> {
private final JsonbConfig cfg = new JsonbConfig().withFormatting(true);
private final Jsonb jsonb = JsonbBuilder.create(cfg);
@Override
public String convertToDatabaseColumn(Rehearsal object) {
if (object == null) {
return null;
}
return jsonb.toJson(object, Rehearsal.class);
}
@Override
public Rehearsal convertToEntityAttribute(String value) {
if (value == null) {
return null;
}
return jsonb.fromJson(value, Rehearsal.class);
}
}

@Mutable is in org.eclipse.persistence.annotations and has no effect on other providers.

Choose the annotation for a Map attribute

Which annotation a java.util.Map attribute needs depends on what its keys and values are.

@ElementCollection is valid for:

  • Map<Basic, Basic>
  • Map<Basic, Embeddable>
  • Map<Embeddable, Basic>
  • Map<Embeddable, Embeddable>
  • Map<Entity, Basic>
  • Map<Entity, Embeddable>

@OneToMany or @ManyToMany is valid for:

  • Map<Basic, Entity>
  • Map<Embeddable, Entity>
  • Map<Entity, Entity>

So a Map<Integer, SomeEntity> cannot be an @ElementCollection; map it with @OneToMany or @ManyToMany and name the key column with @MapKeyColumn.

Map inheritance

JPA offers four ways to map a class hierarchy:

  • Mapped superclass: the parent is not an entity; its fields are copied into each subclass table.
  • Single table: all classes in the hierarchy share one table, and a discriminator column tells the rows apart.
  • Joined: each class has its own table with only its own fields; loading a subclass joins the tables.
  • Table per class: each concrete class has a table with all its fields, inherited ones included, so no join is needed for a single class.

The examples use the same two subclasses; only the parent changes.

@Entity
public class FullTimeEmployee extends Employee {
private int salary;
// constructor, getters, setters
}
@Entity
public class PartTimeEmployee extends Employee {
private int hourlyRate;
// constructor, getters, setters
}

Mapped superclass

@MappedSuperclass
public class Employee {
@Id
private long id;
private String name;
// constructor, getters, setters
}

Employee cannot be queried or referenced in relationships, because it is not an entity.

Single table

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Employee {
@Id
private long id;
private String name;
// constructor, getters, setters
}

The discriminator column is called DTYPE by default and holds the entity name. Customize it with @DiscriminatorColumn on the parent and @DiscriminatorValue on each subclass. Subclass columns must be nullable, since a row only fills the columns of its own class.

Joined

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Employee {
@Id
private long id;
private String name;
// constructor, getters, setters
}

Each subclass table shares the primary key of the employee table. A discriminator column is optional with this strategy; some providers add one by default.

Table per class

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Employee {
@Id
private long id;
private String name;
// constructor, getters, setters
}

Polymorphic queries on Employee need a UNION across all tables. Support for this strategy is optional in the specification.

Resulting tables

Strategy Tables and columns
Mapped superclass full_time_employee(id, name, salary), part_time_employee(id, name, hourly_rate)
Single table employee(id, dtype, name, salary, hourly_rate)
Joined employee(id, name), full_time_employee(id, salary), part_time_employee(id, hourly_rate)
Table per class employee(id, name), full_time_employee(id, name, salary), part_time_employee(id, name, hourly_rate)

References

Related notes

6 min read

SQL joins

INNER, LEFT, RIGHT, FULL OUTER, CROSS and self joins in SQL, with two small example tables, the queries and their results.

  • Databases
3 min read

Database migration: MySQL to PostgreSQL

Migrate a MySQL database to PostgreSQL with pgloader in Docker, and fix the two authentication errors you are likely to hit.

  • Databases
4 min read

Jakarta EE

Jakarta EE 10 and 11: component versions, deployment descriptor headers, Faces namespaces and a multi-module project layout.

  • Java & Jakarta EE

Type to search the whole site.