I have a weird database setup that I’d like to map with hibernate, with a table user
and a table table post
, with a many to many relationship between them, but the relationship is done via a a join table, which is referencing the primary key of user
, but not the primary key of post
, it’s referencing a non unique column of that table.
I managed to map it using @ManyToMany()
with the code below, and it seems to work, but I’m wondering if referencing a non unique column is a good thing or if I shouldn’t because it can break on some edge cases.
user (
id -- pkey
)
post (
id -- pkey
join_id -- non unique
)
user_posts (
user_id -- references user.id
post_join_id -- references post.join_id
)
In java :
public class User {
@Id
long id;
@ManyToMany()
@JoinTable(
name = "user_posts",
joinColumns = @JoinColumn(
name = "user_id",
referencedColumnName = "id"
),
inverseJoinColumns = @JoinColumn(
name = "post_join_id",
referencedColumnName = "join_id"
)
)
Set<Post> posts;
}
public class Post {
@Id
long id;
long join_id;
}
Considering that multiple posts have the same join_id, is that the right way to do that mapping? I can’t find much info about doing such joins on non unique columns.
Thanks.
If your post table already has an ID column which is unique why not use that instead of the join_id column?
In general, referencing a non-unique column in a join table within a @ManyToMany relationship using Hibernate can lead to potential issues. The core issue here is that in a typical @ManyToMany mapping, Hibernate expects the columns used for joins to uniquely identify rows in both tables. If you’re using a non-unique column, it might introduce ambiguities, particularly when fetching or managing the relationships.
Potential issues are:
- Ambiguous Mappings
- Cascading Issues
- Performance Issues