I was wondering what is the best way to map a manyToMany association in JAVA. I have three tables describes like this:
+----------+ +-----------------+ +----------+
| products | | products_stores | | stores |
+----------+ +-----------------+ +----------+
| barecode | | #barecode | | storeID |
| name |----| #storeID |----| location |
+----------+ | price | +----------+
+-----------------+
I was thniking about two ways to reprensent it in JAVA. And I would like to know which one is better in performance or anything.
First way:
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
}
Second way:
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
}
My first thought was the first way, but I also thought about the second way, and I am wondering which one is better, if any. Or if there is another way better than those two.
Thank you.
I would go with three objects, just as you have three DB tables:
Product
describes the product independent on where it's soldStore
describes the storeProductOffer
describes where the product is offered and for how muchDepending on your use case, list of ProductOffer
s may be part of Store
or Product
, or there can be an independent container that manages the relations between products and stores using e.g. a multimap Product
-> List<ProductOffer>
. Or the ProductOffer
may link to both Product
and Store
.
The argument for making a class for the third class is extensibility - it can easily cater for you wanting to consider product availability in the store, for example.