Rich Kroll
Rich Kroll

Reputation: 4005

Hibernate @OneToMany - mapping to multiple join tables

Consider the following domain model:

Issue
- id
- List<Comment>

Entry
- id
- List<Comment>

Comment
-id
-comment

In my design, I was attempting to create two join tables to manage the associations; issue_comments, and entry_comments. I assumed @OneToMany on Issue & Entry, but how do you map the multiple join tables? Using hibernate annotations, how can this be mapped?

Upvotes: 2

Views: 8086

Answers (2)

ChssPly76
ChssPly76

Reputation: 100686

If you can change your domain model, take a look at answer given by cletus. You'll only have one table to update so it'll provide better performance.

If you cannot change your domain model, you can map your comment collections via join tables:

// ENTRY
@OneToMany
@JoinTable(
        name="ENTRY_COMMENTS",
        joinColumns = @JoinColumn( name="entry_id"),
        inverseJoinColumns = @JoinColumn( name="comment_id")
)
public List<Comment> getComments()

// ISSUE
@OneToMany
@JoinTable(
        name="ISSUE_COMMENTS",
        joinColumns = @JoinColumn( name="issue_id"),
        inverseJoinColumns = @JoinColumn( name="comment_id")
)
public List<Comment> getComments()

Your comments would still be in the same table for both issues and entries; only join tables will be different. Note that this is a uni-directional relationship. Details are here

Upvotes: 3

cletus
cletus

Reputation: 625007

This is what's known as an exclusive arc. Don't do it. Instead do this:

Post (id, List<Comment>)
Issue extends Post
Entry extends Post
Comment (id, comment)

In other words, create a common superclass for Issue and Entry and have the comments on that.

Upvotes: 1

Related Questions