繁体   English   中英

连接表中的复合 ID

[英]Composite ID in join-table

我有以下 PostLike class:

@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;
}

class 已经有一个由父 BaseEntity class 提供的 ID 字段。

在用户 class 中,我有以下字段:

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

在 class 后:

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

我希望 PostLike 有一个复合主键,它由 user_id 和 post_id 组成。 提前致谢。

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

@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

使用EmbeddedId注解时, EmbeddedId注解必须只有一个且没有Id注解。

来自Java 持久性与 Hibernate

这种策略的主要优点是双向导航的可能性。 ...
缺点是管理中间实体实例以创建和删除链接所需的代码更复杂,您必须独立保存和删除这些链接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM