@Entity
@Table(name="content")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="content_type",
discriminatorType=DiscriminatorType.STRING
)
class Content implements Serializable {
@Entity declares that this is a persistent object (and that's why Content has to implement Serializable). We could let Hibernate choose the table name but we want to specify a lowercase name (@Table(name="content")). The other annotations define:
@Table(name="content")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="content_type",
discriminatorType=DiscriminatorType.STRING
)
class Content implements Serializable {
- How we want Hibernate to represent the inheritance in the database - as a single sparse table
- How we want Hibernate to distinguish between different types of object in the table - it will add a column called content_type of type varchar (or whatever your database uses for string data)
@Id @GeneratedValue
Long id
Now let's look at one of the extended classes:
Long id
@Entity
@DiscriminatorValue("bookmark")
class Bookmark extends Content {
String link
}
This declares that Bookmark is a persistent object that extends Content and will have its content_type column set to "bookmark". Hibernate will add a column, link, to the content table that will be null for other types of content. Similarly, here's how a comment on a content item is represented:
@DiscriminatorValue("bookmark")
class Bookmark extends Content {
String link
}
@Entity
@DiscriminatorValue("comment")
class Comment extends Content {
// a link to the content item // on which this comment was made @ManyToOne
@JoinTable(name="comment_content")
Content content
}
A comment is content (and can therefore be rated and commented on in turn) and, because this is represented as part of the content table, Hibernate uses an association table for the relationship and we override the default name (which would be content_content) to make it more descriptive. That association table contains two columns: id, the key of the comment, and contentId, the key of the content item on which this comment was made.
That's it.@DiscriminatorValue("comment")
class Comment extends Content {
// a link to the content item // on which this comment was made @ManyToOne
@JoinTable(name="comment_content")
Content content
}

0 responses so far ↓
There are no comments yet...Kick things off by filling out the form below.
Leave a Comment