[英]Best way to map many-to-many association in Java
我想知道在JAVA中映射manyToMany关联的最佳方法是什么。 我有三个表描述如下:
+----------+ +-----------------+ +----------+
| 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
列表可能是Store
或Product
一部分,或者可以有一个独立的容器来管理产品和商店之间的关系,例如使用multimap Product
- > List<ProductOffer>
。 或者ProductOffer
可以链接到Product
和Store
。
为第三类创建类的论点是可扩展性 - 例如,它可以很容易地满足您想要考虑商店中的产品可用性。
取决于您打算如何处理数据。 例如,如果您希望Store对象执行大量查询操作,第二种方法会更好。 在这种情况下,HashMap非常方便,当然会以内存为代价。 但是,如果您主要关注的是存储并且Store类中没有太多重叠,那么第一种方法更好,因为您可以创建一个Product对象列表并继续添加它。
有关您的用例的更多信息将有助于更好地了解您的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.