2015-07-20 37 views
4

我正在使用JPA 2.1hibernate作爲JPA的實現。我想加載一個關係作爲不可變的集合。將JPA集合加載爲不可變

讓我們以employeremployee爲例,將fetchtype設置爲employees字段中的eagar。可以做些什麼來指示JPA將僱員集合加載爲不可變?

+0

從關聯的getter中返回'Collections.unmodifiableSet(employees)'有什麼問題? –

+0

@JBNizet我正在使用lombok來生成getter方法,並且不想手動創建getter方法。 – shailendra

回答

2
  1. 您可以使用@Immutable Hibernate的具體註釋:

    @OneToMany(mappedBy = "employer") 
    @Immutable 
    List<Employee> employees = new ArrayList<>(); 
    
  2. 另一種方法是收集克隆返回它之前:

    假設你有員工的列表,你可以如下圖所示:

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

    通過省略th e setter並且getter只返回備份列表的副本,則可以實現不變性。使用深拷貝克隆(例如org.apache.commons.lang.SerializationUtils)確保整個實體圖被克隆,並因此與受管理的父實體分離。

+0

我將暫時使用@Immutable,但我一直在尋找純粹的JPA解決方案來解決這個問題。 – shailendra

+0

IMO第二種解決方案並不是針對經常訪問的全球數據的最佳解決方案,因爲克隆既會影響性能,也會消耗更多的內存。 – shailendra