Loading JPA collections as immutable

I use JPA 2.1and hibernatehow JPA. I want to download relationships as an immutable collection.

Let's look at an example of objects employerand employeewith the parameter fetchtype, set as eagar field employees. What can be done to instruct the JPAstaff collection to download as immutable?

+4
source share
1 answer
  • You can use @Immutable Hibernate for a specific annotation:

    @OneToMany(mappedBy = "employer")
    @Immutable
    List<Employee> employees = new ArrayList<>();
    
  • Another option is to clone the collection before it returns:

    Assuming you have a list of employees, you can match it as follows:

    @OneToMany(mappedBy = "employer")
    List<Employee> employees = new ArrayList<>();
    
    public List<Employee> getEmployees() {
        return org.apache.commons.lang.SerializationUtils.clone(employees);
    }
    

    setter getter, , . (, org.apache.commons.lang.SerializationUtils) , , , .

+2

Source: https://habr.com/ru/post/1598644/


All Articles