Search code examples
javahibernatedictionarymany-to-many

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.


Solution

  • 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".