我想知道在 JAVA 中映射多对多关联的最佳方法是什么。我有三个表这样描述:
+----------+ +-----------------+ +----------+
| products | | products_stores | | stores |
+----------+ +-----------------+ +----------+
| barecode | | #barecode | | storeID |
| name |----| #storeID |----| location |
+----------+ | price | +----------+
+-----------------+
我正在考虑用 JAVA 表示它的两种方法。我想知道哪个在性能或其他方面更好。
第一种方式:
public class Product {
private String name;
private String barecode;
private double price;
private Store store;
public Product(String name, String barecode, double price, Store store){/*...*/}
//getter/setter
}
public class Store {
private String name;
private String location;
public Store(String name, String location){/*...*/}
//getter/setter
}
第二种方式:
public class Product {
private String name;
private String barecode;
private HashMap<Store, double> priceList;
public Product(String name, String barecode, HashMap<Store, double> priceList){//}
//getter/setter
}
public class Store {
private String name;
private String location;
public Store(String name, String location){/*...*/}
//getter/setter
}
我首先想到的是第一种方式,但我也想到了第二种方式,我想知道哪种方式更好,如果有的话。或者是否有比这两种更好的方法。
谢谢。
最佳答案
我会选择三个对象,就像您有三个数据库表一样:
-
Product
独立于销售地点描述产品 -
Store
描述商店 -
ProductOffer
描述提供产品的地点和价格
根据您的用例,ProductOffer
列表s 可能是 Store
的一部分或 Product
,或者可以有一个独立的容器来管理产品和商店之间的关系,例如使用多图 Product
-> List<ProductOffer>
.或者 ProductOffer
可以同时链接到 Product
和 Store
.
为第三类创建一个类的理由是可扩展性 - 例如,它可以轻松满足您想要考虑商店中产品可用性的需求。
关于java - 在 Java 中映射多对多关联的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33283943/