2015-11-03 58 views
0

懶惰的關係,我有:實例化VStateBE這樣的事情之前,系列化

@OneToMany(mappedBy = "vState", fetch = FetchType.LAZY) 
private Set<VOptionBE> vOptions; 

@Override 
public Set<String> getSaList() { 

    if (saList == null) { 
     saList = new TreeSet<String>(); 
     for (final VOptionBE option : vOptions) { 
      saList.add(normalizeSACode(option.getSa())); 
     } 
    } 
    return saList; 

,並在其他類VOptionBE我:

@Id 
@Column(name = "SA", length = 4) 
private String sa; 

@ManyToOne 
@JoinColumn(name = "V_SHORT") 
private VStateBE vState; 

我收到以下錯誤:

Caused by: Exception [EclipseLink-7242] (Eclipse Persistence Services - 2.3.4.v20130626-0ab9c4c): org.eclipse.persistence.exceptions.ValidationException 
Exception Description: An attempt was made to traverse a relationship using indirection that had a null Session. This often occurs when an entity with an uninstantiated LAZY relationship is serialized and that lazy relationship is traversed after serialization. To avoid this issue, instantiate the LAZY relationship prior to serialization. 

它嘗試從getSaList()方法讀取時發生。

回答

0

我推薦找出爲什麼(德)序列化發生,因爲這種類型的錯誤不常見於常見用例。最常見的解決方案是之前預先加載所有數據。

無論如何,如果你想確保懶惰數據序列化之前總是加載,它可以幫助實現對VStateBE類自己的序列化方法加載懶惰集合之前對象序列化。只需編寫自己的writeObject方法,如下所示:

@Entity 
public class VStateBE implements Serializable { 
    @OneToMany(mappedBy = "vState", fetch = FetchType.LAZY) 
    private Set<VOptionBE> vOptions; 

    // add method like this: 
    private void writeObject(ObjectOutputStream stream) 
     throws IOException { 
    vOptions.isEmpty(); // this will load lazy data in a portable way 
    stream.defaultWriteObject(); // this will continue serializing your object in usual way 
    } 
}