Hibernate version:
2.1.8
I'm trying to work with an existing database schema and am having difficulty with the mapping documents to allow me to persist duplicate data to a table.
I have an ALBUM and a TRACK table. The business logic tells me that an ALBUM can have many TRACK's and a track can be in many ALBUM's.
So what I would eventually like to have is something like
Code:
ALBUM Table
ALBUM_ID | ALBUM_NAME
------------------------------
1 | Album One
------------------------------
2 | Album Two
------------------------------
3 | Album Three
and
TRACK Table
TRACK_ID | NAME | ALBUM_ID
------------------------------------------
1 | Track One | 1
------------------------------------------
2 | Track Two | 1
------------------------------------------
3 | Track One | 2
------------------------------------------
4 | Track Two | 3
My mapping document is using a Set and looks as follows.
Code:
<class name="Album" table="ALBUM">
<id name="id" type="int" column="ALBUM_ID">
<meta attribute="scope-set">protected</meta>
<generator class="native"/>
</id>
<property name="albumName" column="NAME" type="string"/>
<set
name="albumTrack"
lazy="true"
cascade="save-update">
<key column="ALBUM_ID"/>
<one-to-many class="com.kbilly.hibernate.Track"/>
</set>
</class>
I know that a Set won't do though as it doesn't allow duplicates and this is why I get.
Code:
TRACK Table
TRACK_ID | NAME | ALBUM_ID
------------------------------------------
1 | Track One | 3
------------------------------------------
2 | Track Two | 2
The code I use to persist the data looks like this.
Code:
Track t1 = new Track();
t1.setTrackName("Track One");
Track t2 = new Track();
t2.setTrackName("Track Two");
Album one = new Album();
one.setAlbumName("Album One");
Album two = new Album();
two.setAlbumName("Album Two");
Album three = new Album();
three.setAlbumName("Album Three");
HashSet set1 = new HashSet();
set1.add(t1);
set1.add(t2);
HashSet set2 = new HashSet();
set2.add(t1);
HashSet set3 = new HashSet();
set3.add(t2);
one.setAlbumTrack(set1);
two.setAlbumTrack(set2);
three.setAlbumTrack(set3);
Connection conn = new Connection();
try {
conn.create();
Session session = new Connection().getSession();
Transaction tx = session.beginTransaction();
save(one,session);
save(two,session);
save(three,session);
tx.commit();
conn.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I've tried to use <idbag> but I can only get this working with an association table, ALBUM_TRACK for instance. But the database schema I'm working with doesn't have this join table.
So my quesxtion is how do I implement <idbag> to allow duplicates in the the TRACK table without using a join table?
Any help would be really appreciated with this.
Regards,
Kevin