在 Java 中映射多对多关联的最佳方式

Best way to map many-to-many association in Java

我想知道在 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
    }

我首先想到的是第一种方式,但我也想到了第二种方式,如果有的话,我想知道哪种更好。或者如果有比这两个更好的方法。

谢谢。

取决于您打算如何处理数据。例如,如果您希望通过 Store 对象执行大量查询操作,则第二种方法更好。在那种情况下,HashMap 非常方便,当然是以内存为代价的。但是,如果您主要关心的是存储并且 Store 中没有太多重叠 class,那么第一种方法更好,因为您可以只创建一个 Product 对象列表并不断向其中添加内容。

有关您的用例的更多信息将有助于更好地了解您的情况。

我会选择三个对象,就像您有三个数据库表一样:

  • Product 独立于销售地点描述产品
  • Store描述店铺
  • ProductOffer 描述产品的销售地点和价格

根据您的用例,ProductOffer 的列表可能是 StoreProduct 的一部分,或者可以有一个独立的容器来管理产品和商店之间的关系使用例如多图 Product -> List<ProductOffer>。或者 ProductOffer 可能 link 到 ProductStore

为第三个 class 创建 class 的理由是可扩展性 - 例如,它可以轻松满足您想要考虑商店中产品可用性的需求。