Skip to content
Advertisement

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?

Advertisement

Answer

  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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement