I have a many-to-one relationship defined between 2 classes (MusicFile and Category). The idea is that each MusicFile object can have an associated Category. That means that 2 different MusicFile objects can have the same Category.
I have the relationship defined as follows:
Code:
<hibernate-mapping>
<class name="music.beans.MusicFile" table="musicfile">
<id name="id" column="id" type="long">
<generator class="identity"/>
</id>
<many-to-one name="category" column="cat_name" class="music.beans.Category" cascade="all"/>
<property name="album"/>
<property name="artist"/>
<property name="serverURL"/>
<property name="title"/>
</class>
<class name="music.beans.Category" table="category">
<id name="name" column="name" type="string">
<generator class="assigned"/>
</id>
</class>
</hibernate-mapping>
Now, I try to add the following:
MusicFile1 (id=1, name="file1", category="cat1")
MusicFile2 (id=2, name="file2", category="cat1")
Since I have cascade="all" specified the Category object is added when I do a session.save() on the MusicFile. It works for MusicFile1, but MusicFile2 throws an SQLException because "cat1" already exists.
My question is - how do I get around this with Hibernate? Or do I have to turn off cascading and add the Categories before I add the MusicFiles? I thought that there might be some way to say for Category that if it already existed then don't add it.
Any help is appreciated.