Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: mapping many-to-many to Map

I am developing an application which deals with two following entities: Products (let's name it as X, Y, Z) and Materials (a, b, c, ...). It's known that every product has a recipe which indicates what materials are required for making this product. For example, to produce one X we need 2 a, 6 c and 4 d (X = 2a + 6c + 4d).

That's how it reflects in a database tables:

Products
id INT
name VARCHAR
...

Materials
id INT
name VARCHAR
...

Recipes
product_id INT
material_id INT
count INT

The "count" field in the third table is a coefficient for materials of the same kind (2, 6, 4 from the example).

So I want to compose Product class this way:

public class Product {
    ...
    private Map<Material, Integer> recipe; // How many units of each material we need?
    ...
}

Is it a way to fetch all the necessary data for recipe Map using Hibernate? The separate configuration approach (without annotations) is preferred.

like image 380
Ivan Stepuk Avatar asked Dec 01 '10 18:12

Ivan Stepuk


1 Answers

Since nobody posted the solution without annotations, I'll show the solution with JPA 2.0 @ElementCollection annotation:

@ElementCollection
@CollectionTable(name = "Recipes", 
    joinColumns = @JoinColumn(name = "product_id"))
@MapKeyJoinColumn(name = "material_id")
@Column(name = "count")
private Map<Material, Integer> recipe;

Also note that since class of values of your map is Integer, solution without annotations is likely to be documented as "collection mapping" rather than "entity relationship mapping".

like image 83
axtavt Avatar answered Oct 21 '22 14:10

axtavt