1 Reply Latest reply on Jul 17, 2008 3:35 AM by celle2006

    Hibernate bidirectional many-to-many issues

    Ioannis Mavroukakis Newbie

      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;
      


      This is the code that saves the User object


      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();
      


      The problem is that when I save the User object, it is persisted along with the Recipe object, however the table that is supposed to contain the many-to-many relationship of Recipe-Ingredient is empty. Can anyone shed some light on what I am doing wrong?

      Thanks!