我在 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() 方法读取时会发生这种情况。
最佳答案
我建议找出为什么会发生(反)序列化,因为这种类型的错误在常见用例中并不常见。最常见的解决方案是之前预加载所有数据。
无论如何,如果您想确保始终在序列化之前加载惰性数据,那么在 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
}
}
关于java - 在序列化之前实例化 LAZY 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33506978/