I am using JPA 2.1 and Hibernate as a JPA implementation, and I want to load a relationship as an immutable collection.
Let’s take an example of an Employer
parent entity that has an employees
child collection.
What can be done to instruct JPA to load an immutable employees
collection?
Advertisement
Answer
You can use the @Immutable Hibernate specific annotation:
@OneToMany(mappedBy = "employer") @Immutable List<Employee> employees = new ArrayList<>();
Another option is to clone the collection prior to returning it:
Assuming you have a List of employees, you can map it like this:
@OneToMany(mappedBy = "employer") List<Employee> employees = new ArrayList<>(); public List<Employee> getEmployees() { return org.apache.commons.lang.SerializationUtils.clone(employees); }
By omitting the
setter
and having thegetter
return only a copy of the backed list, you can achieve immutability. Using deep-copy cloning (e.g.org.apache.commons.lang.SerializationUtils
) ensures the whole entity graph is cloned and therefore decoupled from the managed parent entity.