Hi,
I'm trying to play around with hibernate annotations, I'm coming up against a brick wall with a certain issue regarding a many to many relationship.
@Entity public class Recipe implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "recipe_id") private Long id; @ManyToOne @JoinColumn(name="user_fk") private User user; @ManyToMany( targetEntity=gr.zymari.entities.Ingredient.class, cascade={CascadeType.ALL, CascadeType.MERGE} ) @JoinTable( name="Recipe_Ingredients", joinColumns = @JoinColumn( name = "recp_id"), inverseJoinColumns = @JoinColumn( name = "ingr_id") ) private Set<Ingredient> ingredients;
public class Ingredient implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ingredient_id") private Long id; private Integer quantity; private String name; @ManyToMany( cascade = {CascadeType.ALL, CascadeType.MERGE}, mappedBy= "ingredients", targetEntity=Recipe.class ) private Set<Recipe> recipies;
@Entity public class User implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "user_id") private Long id; @OneToMany(mappedBy="user" ,cascade = {CascadeType.ALL, CascadeType.MERGE}) private Set<Recipe> recipies;
Transaction tx = getHibSession().beginTransaction(); tx.begin(); Ingredient blackStuff = new Ingredient(); blackStuff.setName("Chocolate"); blackStuff.setMeasure(Measure.GRAM); blackStuff.setQuantity(100); recipe.addIngredient(blackStuff); user.addRecipe(recipe); recipe.setUser(user); getHibSession().saveOrUpdate(user); tx.commit();
Hi imavroukakis!
I think you forgot following code:
blackStuff.addRecipe(recipe);