I am having trouble setting up jpa mappings for some entities. Below is the scenario I want to implement.
There are 3 tables :
Below is the code I have tried to implement, but It's not working
@Entity(name = "likes")
@IdClass(LikesId.class)
public class Likes {
@Id
@ManyToOne(optional = false)
@JoinColumn(name = "post_id")
private Post post;
@Id
@ManyToOne(optional = false)
@JoinColumn(name = "user_id")
private User user;
@UpdateTimestamp
private Date timestamp;
public Like (Post post, User user){
this.setPost(post);
this.setUser(user);
}
}
Below is IdClass for composite key :
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class LikesId implements Serializable {
@ManyToOne(optional = false)
@JoinColumn(name = "post_id")
private Post post;
@ManyToOne(optional = false)
@JoinColumn(name = "user_id")
private User user;
}
I am getting below error on saveAndFlush call :
java.lang.IllegalArgumentException: Can not set com.app.models.post.Post field com.app.models.likes.LikesId.post to java.lang.Long
Your id class should look like below.
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class LikesId implements Serializable {
private Long postId;
private Long userId;
}