O'Reilly logo

Hibernate: A Developer's Notebook by James Elliott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.4. Lifecycle Associations

Hibernate is completely responsible for managing the ALBUM_TRACKS table, adding and deleting rows (and, if necessary, renumbering POSITION values) as entries are added to or removed from Album beans' tracks properties. You can test this by writing a test program to delete the second track from our test album and see the result. A very quick and dirty way to do this would be to add the following four lines (see Example 5-11) right after the existing tx.commit() line in Example 5-7 and then run ant schema ctest atest db.

Example 5-11. Deleting our album's second track
tx = session.beginTransaction();
album.getTracks().remove(1);
session.update(album);
tx.commit();

Doing so changes the contents of ALBUM_TRACKS as shown in Figure 5-4 (compare this with the original contents in Figure 5-3). The second record has been removed (remember that Java list elements are indexed starting with zero), and POSITION has been adjusted so that it retains its consecutive nature, corresponding to the indices of the list elements (the values you'd use when calling tracks.get()).

Figure 5-4. Album track associations after deleting our album's second track

This happens because Hibernate understands that this list is "owned" by the Album record, and that the "lifecycles" of the two objects are intimately connected. This notion of lifecycle becomes more clear if you consider what happens ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required