Reputation: 273452
I have Shipment and Product entities. Each shipment consists of any amount of any numbers of products. I.e. a shipment has a field named products which is a java.util.Map where they key is the product being shipped and the value is the number of instances of that product being shipped.
How do I map that to a db with hibernate annotations?
Upvotes: 1
Views: 762
Reputation: 273452
This is what you have to do. The field map
belongs to the Shipment
class, and it maps each Product
to the number of products shipped.
This will not work unless you properly define equals and hashCode methods in the class Product that do not depend on hibernate generated ids. (Or read the full story here).
@CollectionOfElements(targetElement=Integer.class)
@MapKeyManyToMany(targetEntity=Product.class)
private Map<Product, Integer> map = new HashMap<Product, Integer>();
Upvotes: 1
Reputation: 32283
This seems like a bit of an odd design to me, but if I understand correctly you'll want a database schema that has:
This is all kind of basic, as the relation is a basic one-to-many relationship from the shipment side and many-to-one on the reverse of course. I could give you examples but really the hibernate docs (scroll down to bottom for a map example) seem to have that covered. Some really hard thinking about how that xml maps to the annotations should tide you over. If you're trying to do it in pure JPA you might turn into some trouble, as the linked example seems to use formula.
Upvotes: 0