I have not been able to come up with a mapping that works for the following scenario:
Code:
class Recipe
{
List<IngredientQty>ingredients;
int id;
}
class Ingredient
{
int id;
}
class IngredientQty
{
Recipe recipe;
Ingredient ingredient;
double qty;
}
I've tried numerous things but none of them have worked. My first reaction, after reading documentation was:
Code:
@Entity
@Table(name="recipe")
class Recipe implements Serializable
{
@OneToMany(targetEntity = IngredientQty.class)
@JoinColumn(name="recipe_id")
List<IngredientQty>ingredients;
@Id
@Column(name="id")
int id;
}
@Entity
@Table(name="ingredient")
class Ingredient implements Serializable
{
@Id
@Column(name="id")
int id;
}
@IdClass(IngredientQtyPK.class)
@Entity
@Table(name="recipe_x_ingredient")
class IngredientQty implements Serializable
{
@Id
@ManyToOne
@JoinColumn(name="recipe_id")
Recipe recipe;
@Id
@ManyToOne
@JoinColumn(name="ingredient_id")
Ingredient ingredient;
@Column(name="qty")
double qty;
}
@Embeddable
class IngredientQtyPK implements Serializable
{
Recipe recipe;
Ingredient ingredient;
//I also implement hashcode and equals,
}
I've also tried using the embeddedId solution, but again, with no success. Either I get an error from hibernate that it can't serialize integer columns to complex objects, or it tries to retrieve a column named "recipe" from the recipe_x_ingredient table.
I did manage to make the whole thing work if I change all of my complex objects to simple integers, but that is not very helpful, since I then need a global singleton to be able to get back to my objects (which not only is yucky but also limits other functionality I need)
P.S. I've simplified the code, hopefully haven't broken it too much on the way.
Please help!