I have Many to Many relationship between 2 entities: Item and ItemCategory
In class Item
@ManyToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE})
@JoinTable(
name="LINK_ITEM_CATEGORY",
joinColumns={@JoinColumn(name="ITEM_ID")},
inverseJoinColumns={@JoinColumn(name="CATEGORY_ID")}
)
private Set<ItemCategory> associatedCategories = new HashSet<ItemCategory>();
In class ItemCategory
@Column(name="NAME")
private String name;
@ManyToMany(mappedBy="associatedCategories")
private Collection<Item> comprisesExpenditure = new ArrayList<Item>();
开发者_运维知识库Whenever I try to save an Item, categories added to Set associatedCategories
are saved even if a category by the same name
exists in database. Is there some way for hibernate to search for Categories based on name
and create a link with existing one, instead of creating a new Category and linking Item with the new one.
To have this working properly you have to implement hashCode and equals methods properly. Without this HashSet may behave unpredicatably.
No. Since name is not the ID of the category, you may have severa categories with the same name. You might add a unique constraint, but Hibernate can't magically know that the ne category you add in the set should in fact be an existing category having the same name.
When creating categories and adding them to the set, you should search for a category having the same name and, if it exists, put this existing category in the set instead of a new one.
精彩评论