Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map an immutable collection with JPA and Hibernate

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?

like image 934
MechCloud Avatar asked Jul 20 '15 04:07

MechCloud


1 Answers

  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.

like image 191
Vlad Mihalcea Avatar answered Sep 18 '22 01:09

Vlad Mihalcea