我的实体包含以下私有ForeignCollection
属性:
@ForeignCollectionField
private ForeignCollection<Order> orderCollection;
private List<Order> orderList;
避免让来电者使用ForeignCollection
的最佳方法或通常方法是什么?有没有任何简洁的方法可以将Collections
数据返回给调用者?
以下方法如何显示?它允许呼叫者通过List
访问数据。你会建议这样做吗?
public List<Order> getOrders() {
if (orderList == null) {
orderList = new ArrayList<Order>();
for (Order order : orderCollection) {
orderList.add(order);
}
}
return orderList;
}
答案 0 :(得分:3)
如果可以将签名更改为Collection
而不是List
,则可以尝试使用Collections.unmodifiableCollection()。
public Collection<Order> getOrders()
{
return Collections.unmodifiableCollection(orderCollection);
}
否则,您使用惰性成员变量的方法很好(假设您不需要同步)。另请注意,您只需使用ArrayList
的构造函数来复制源集合中的值:
orderList = new ArrayList<Order>(orderCollection);