7

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?

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Shailendra
  • 319
  • 4
  • 14
  • What's the problem in returning `Collections.unmodifiableSet(employees)` from the getter of your association? – JB Nizet Jul 20 '15 at 06:10
  • @JBNizet I am using lombok for generating getter method and don't want to create getter method manually. – Shailendra Jul 21 '15 at 04:02

1 Answers1

5
  1. You can use the @Immutable Hibernate specific annotation:

    @OneToMany(mappedBy = "employer")
    @Immutable
    List<Employee> employees = new ArrayList<>();
    
  2. 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 the getter 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.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • I will go with @Immutable for the time being but I was looking for pure JPA solution for this problem. – Shailendra Jul 21 '15 at 13:14
  • 1
    IMO second solution is not an optimal solution for global data which is accessed frequently as cloning will both impact performance as well as consume more memory. – Shailendra Jul 21 '15 at 13:20