簡體   English   中英

在Java中映射多對多關聯的最佳方法

[英]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列表可能是StoreProduct一部分,或者可以有一個獨立的容器來管理產品和商店之間的關系,例如使用multimap Product - > List<ProductOffer> 或者ProductOffer可以鏈接到ProductStore

為第三類創建類的論點是可擴展性 - 例如,它可以很容易地滿足您想要考慮商店中的產品可用性。

取決於您打算如何處理數據。 例如,如果您希望Store對象執行大量查詢操作,第二種方法會更好。 在這種情況下,HashMap非常方便,當然會以內存為代價。 但是,如果您主要關注的是存儲並且Store類中沒有太多重疊,那么第一種方法更好,因為您可以創建一個Product對象列表並繼續添加它。

有關您的用例的更多信息將有助於更好地了解您的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM