有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jointable中的java复合ID

我有以下类似PostLike的课程:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PostLike extends BaseEntity {

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "post_id")
    private Post post;
}

该类已具有父BaseEntity类提供的ID字段

在User类中,我有以下字段:

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
Set<PostLike> userLikes = new HashSet<PostLike>();

在后课堂上:

@OneToMany(mappedBy = "post")
private Set<PostLike> postLikes = new HashSet<PostLike>();

我希望PostLike有一个复合主键,它由用户id和post id组成。 提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    作为一种方法,您可以使用@EmbeddedId注释并使用可嵌入类表示此复合键:

    @Entity
    public class PostLike {
    
        @Embeddable
        private static class Id implements Serializable {
    
            @Column(name = "user_id")
            private Long userId;
    
            @Column(name = "post_id") 
            private Long postId;
    
            public Id() {
            }
    
            public Id(Long userId, Long postId) {
                this.userId = userId;
                this.postId = postId;
            }
    
            // equals and hashCode
        }
    
        @EmbeddedId
        Id id = new Id();
    
        @ManyToOne
        @JoinColumn(name = "user_id")
        private User user;
    
        @ManyToOne
        @JoinColumn(name = "post_id")
        private Post post;
    
    
        public PostLike() {
        }
    
        public PostLike(User user , Post post) {
            this.user = user;
            this.post = post;
    
            this.id.postId = post.getId();
            this.id.userId = user.getId();
    
            post.getUserLikes().add(this);
            user.getUserLikes().add(this);
        }
            ... // getters and setters
    }
    

    一些注释:
    来自@EmbeddedId的javadoc

    There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation is used.

    Java Persistence with Hibernate

    The primary advantage of this strategy is the possibility for bidirectional navigation. ...
    A disadvantage is the more complex code needed to manage the intermediate entity instances to create and remove links, which you have to save and delete independently.