我有一刀切的申请,使用JPA。
Say I有一个名为Product
的实体,名称和price
属性(all entities with an id
自然,我可以很容易地获得<代码>List<Product>(来自查询或其他实体),但我往往希望有<代码>List<String>(产品名称清单)或List<Long>
(产品价格清单或产品清单)。
绕过整个<代码>Product<>/code”的时间很多,但有两个情况我不想这样做:
- I m passing the list to a class which shouldn t have a dependency on the
Product
class. - It s significantly easier/faster to get a list of ids than full product objects, (but in some cases I already have them).
这样做的阴险方式如下:
List<Long> productIds = new ArrayList<Long>();
for(Product product: products) {
productIds.add(product.getId());
}
但是,我不喜欢这样做,因为这种情况令人迷惑,效率低下。 在座各位:
[ p.id for p in products ]
我在 Java的“最佳”就是:
public class ProductIdList extends AbstractList<Long> {
private List<Product> data;
public ProductIdList(List<Product> data) {
this.data = data;
}
public Long get(int i) {
return data.get(i).getId();
}
public int size() {
return data.size();
}
public Long remove(int i) {
return data.remove(i).getId();
}
/* For better performance */
public void clear() {
data.clear();
}
/* Other operations unsupported */
}
建议:
- This approach doesn t need to copy the data
- It is a true "view" on the data - changes to the underlying list are reflected.
意见:
- Seems like a lot of code
- Need a class like this for each attribute I want to access like this
因此,这是一个好的想法吗? 难道我只是要提出次要名单吗? 是否考虑了第三种选择: