Issue
I am having some catalogs, under these catalogs there are some categories some catalogs doesn't have any categories at all and finally there are products under various categories or catalogs.
for example catalog Household will have a category Kitchen which then will have products like oven, plates, dishwasher etc while product bed-sheets will directly belong to catalog households and not to any category
same way catalog chemicals will not have any category and will only have products.
below things are certain
i) All the products belongs to some catalogs
ii) some catalogs will have categories and then categories will have products
iii) some products will only belong to catalogs and never associate with any category
I have come up with below Model classes structure but I am not sure that How they will handle the above case , can you please suggest something ?
@Entity
public class Catalogs {
@OneToMany(CascadeType.All, orphanRemoval = true)
@JoinColumn(name = "catalogs_id")
private Set<Categories> categories;
/* rest of the code will go here */
}
my categories class will be like this
@Entity
public class Categories {
@OneToMany(CascadeType.All, orphanRemoval = true)
@JoinColumn(name = "categories_id")
private Set<Products> products;
}
finally my Products class will go like this
@Entity
public class Products {
/* Products related codes */
}
or should I also have a field for products in my catalog class ? like below
@Entity
public class Catalogs {
@OneToMany(CascadeType.All, orphanRemoval = true)
@JoinColumn(name = "catalog_id")
private Set<Categories> categories;
@OneToMany(CascadeType.All, orphanRemoval = true)
@JoinColumn(name = "catalog_id")
private Set<Products> products;
/* rest of the code will go here */
}
Solution
According to your requirement, I got an approach in my mind. If I start from Catalog, I would consider that class as root. Then I would design that class as
@Entity
public class Catalogs {
// just catalog name or other activity. not mapping
}
After that one, I would design category class like this, where every category would be under a catalog.
@Entity
public class Categories {
// other attribute...
@ManyToOne
@JoinColumn(name = "catalog_id")
private Catalogs catalogs;
}
After these, I would design my product class like this. As you said one product may be under catalog or maybe under a category. So I made some attribute nullable.
@Entity
public class Products {
//other attributes....
@ManyToOne
@JoinColumn(name = "catalog_id")
@Nullable
private Catalogs catalogs;
@ManyToOne
@JoinColumn(name = "category_id")
@Nullable
private Categories categories;
}
Check this approach. And response about your opinion.
Answered By - Avijit Barua