0

I am having trouble setting up jpa mappings for some entities. Below is the scenario I want to implement.

There are 3 tables :

  1. Users: stores the user information. ( Auto Generated Id is Primary key )
  2. Posts: stores the Feed posted by a company. ( Auto Generated Id is Primary key )
  3. Likes: stores the Feeds liked by User. ( User-Id, Post-Id as composite Primary key )

enter image description here

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
Vishal Tank
  • 153
  • 2
  • 7

1 Answers1

1

Your id class should look like below.

@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class LikesId implements Serializable {

    private Long postId;

    private Long userId;

}
SSK
  • 3,444
  • 6
  • 32
  • 59
  • I have tried that already, but that way I am unable to use @ManyToOne relation in Likes Model. I am getting below error on server start : Unable to find properties (postId, userId) in entity annotated with com.app.models.likes.Like Hence to resolve this I have to add all 4 postId, userId, post, user in Likes model. – Vishal Tank Jul 10 '21 at 06:07
  • Yes, you have to add all 4 postId, userId, post, user in Likes model, two of them might be needed insertable and updatable false – SSK Jul 10 '21 at 06:44