Maps with Spring Data JPA
March 18, 2024
Introduction #
This small article explores one way of using Maps for data modelling in a JPA (Java Persistence API) based application.
Model #
Imagine we have the following data model:
classDiagram User "1" *-- "*" Account : manages
This means:
A user has one bank account per account type.
Accounts do not need to be aware of their ‘owner’.
We need to have access to all user accounts, preferably by account type.
Implementation #
In order to model these requirements in a JPA application one may do as follow:
public class User implements Serializable{
@OneToMany(targetEntity = Account.class, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "USER_ID")
@MapKey(name = "accountType")
private final Map<String, Account> accounts;
...
}
The column “USER_ID” needs not be defined at the Account level since it is used exclusively for wiring objects at the database level but not at the object level.
This way the relation stays unidirectional.
public class Account implements Serializable{
@Id
private final String accountNumber;
...
private String accountType;
...
}