OneToMany JoinTable with a non Primary Key value
-
27-10-2019 - |
Question
I'm trying to replicate Facebook's wall in Java EE.
I've got 3 tables: User, Post, Wall.
User has an username(PK) and other fields, Post has an id(PK), an author(FK on User) and some other. Wall is a Join Table between Post and User.
The point is that the project compiles only if I have, in Wall, both post and user as PK. Having Post has PK and User just as a non null value won't work !
But having both of them as PK leads to a @ManyToMany, which means that the same post can be on many Walls, which is incorrect !
I've tried having just Post as PK in Wall and using this mapping :
Post:
@JoinTable(name = "Wall", joinColumns = {
@JoinColumn(name = "id", referencedColumnName = "id")}, inverseJoinColumns = {
@JoinColumn(name = "user", referencedColumnName = "username")})
@OneToMany
private User user;
User:
@ManyToOne
private Collection<Post> onWall;
but it says :
The target entity of the relationship attribute [user] on the class [class entity.Post] cannot be determined. When not using generics, ensure the target entity is defined on the relationship mapping..
What's wrong with my mapping?
Solution
How about two relationships User-to-Post, one for wall, one for authorship:
- User one-to-many to Post (posts stuck to user's wall, no join table),
- User one-to-many to Post (post's author),
with reverse relationships as needed.
For example:
@Entity
public class User {
@OneToMany(mappedBy="onWall")
private Collection<Post> wall;
// You can skip this relationship, if you don't want it
@OneToMany(mappedBy="author")
private Collection<Post> authoredPosts;
}
@Entity
public class Post {
@ManyToOne
@JoinColumn(name="wallOwnerId")
private User onWall;
@ManyToOne
@JoinColumn(name="authorId")
private User author;
}