[英]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.