spring-bootforeign-keyscomposite-primary-keycomposite-keyspring-boot-jpa

Spring boot JPA composite foreign key mapping


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

Solution

  • Your id class should look like below.

    @NoArgsConstructor
    @AllArgsConstructor
    @EqualsAndHashCode
    public class LikesId implements Serializable {
    
        private Long postId;
    
        private Long userId;
    
    }