Video in progress
A comment can belong to several types of object (post, photo, video). How do you model such a polymorphic association in Hibernate?
There are three ways: Hibernate's @Any with a (target_type, target_id) pair, a separate nullable FK column for each type, or inheritance with a shared parent entity (Commentable). @Any is flexible but has no FK, so the database can't check data integrity. When the number of types is small, I prefer separate FK columns.
📖 Answer
@Any, a "polymorphic FK":
@Entity
class Comment {
@Id @GeneratedValue Long id;
@Any
@AnyDiscriminator(DiscriminatorType.STRING)
@AnyDiscriminatorValue(discriminator = "POST", entity = Post.class)
@AnyDiscriminatorValue(discriminator = "PHOTO", entity = Photo.class)
@AnyKeyJavaClass(Long.class)
@Column(name = "target_type")
@JoinColumn(name = "target_id")
private Object target;
}
One table, and adding a new type is easy. But you can't put an FK on target_id: if a post is deleted, its comments are left "orphaned". Joining in JPQL is awkward, and you create the index on (target_type, target_id) yourself.
- Separate columns:
create table comment (
id bigint primary key,
post_id bigint references post(id),
photo_id bigint references photo(id),
check (num_nonnulls(post_id, photo_id) = 1)
);
In the entity there are two plain @ManyToOnes. FKs, cascade, joins: everything works as usual. With 2-4 types, this is the most reliable option.
- Inheritance:
PostandPhotoinherit from a commonCommentableentity (JOINED), and the comment has@ManyToOne Commentable. There is an FK, but now every post read comes with an extra join, and changing the inheritance hierarchy later is hard.
I usually start with option 2. I use @Any where there are many types, new ones get added quickly, and integrity can be checked at the application level (audit, notifications).
Sign up to mark studied questions and save your progress.