O'Reilly logo

Harnessing Hibernate by James Elliott, Ryan Fowler, Timothy M. O'Brien

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

An Alternate Approach

This exercise has shown that annotations are clearly a viable way of mapping model classes. By jumping through a few hoops we were able to maintain the exact schema we’d evolved in the preceding chapters, though we lost the ability to cascade creation of Tracks during the creation of an Album. There’s another approach we could have taken in the schema which would maintain that automatic cascade, and give us some other abilities, as well, if we think about the AlbumTrack class slightly differently.

Mapping AlbumTrack as a full-blown entity gives us places to put cascade annotations that Hibernate will honor all the way from the Album definition to the embedded Track reference. It also gives us a few new complications to think about, but some of those can be seen as opportunities. First of all, AlbumTrack as an entity will need an ID. And since we will then be able to get our hands on AlbumTrack objects without starting from an Album, the AlbumTrack model ought to be enhanced to expose the link back to the ALBUM table from the ALBUM_TRACKS table (which used to be hidden in Hibernate’s composite key). We’d achieve that by adding an album property. Example 7-12 shows the key parts of the AlbumTrack mapping as they would differ in this approach.

Example 7-12. Annotating the AlbumTrack class as an entity

package com.oreilly.hh.data;

import java.io.Serializable;
import javax.persistence.*;
@Entity 
@Table(name="ALBUM_TRACKS")
public class AlbumTrack {

    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) ...

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