1

I have a problem with cascade deleting in Hibernate 3.6. I have the following many to many relationship between two entity classes: Menu and Item. Note that this is a uni-directional relationship. A Menu instance has a reference the set of Items it has. But an Item instances do not know about Menu instances it belongs to.

@Entity
public class Menu {

    @Id
    private Long id;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(
        name = "Menu_Item",
        joinColumns = {@JoinColumn(name = "menu_id")}
        inverseJoinColumns = {@JoinColumn(name = "item_id")},
    )
    private Set<Item> items = new HashSet<Item>();

    ....
}


@Entity
public class Item { 
    @Id  
    private Long id; 

    private String name;

    private String code;

    ...
}

My requirement: An row in the Item table should exist in the database only if at least one Menu entry refers to it. That is, an item that does not belong to any menu should not exist in the database.

Now, assume the following scenario,

menu1 has [item1, item2]

menu2 has [item1]

When I invoke session.remove(menu1), Hibernate tries to remove both item1 and item2 from the Item table (this operation is actually rejected by the dataset). I want Hibernate to remove only item2, since there is another menu using item1.

I'm aware that I can prevent associated Items being deleted when a Menu is deleted by making cascade not include CascadeType.DELETE. But I don't want this behavior either: I do want item2 to be deleted from the database (since no menu is using it, i.e., it has no associations in the Menu_Item table).

What is the best to achieve this in Hibernate?

0 Answers0