简体   繁体   English

连接表中的复合 ID

[英]Composite ID in join-table

I have the following PostLike class:我有以下 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;
}

The class already has an ID field provided by parent BaseEntity class. class 已经有一个由父 BaseEntity class 提供的 ID 字段。

In the User class, I have the following field:在用户 class 中,我有以下字段:

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

And in the Post class:在 class 后:

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

I want a PostLike to have a composite primary key, which consists of user_id and post_id.我希望 PostLike 有一个复合主键,它由 user_id 和 post_id 组成。 Thanks in advance.提前致谢。

As one way to do this you can use @EmbeddedId annotation and express this composite key with embeddable class:作为一种方法,您可以使用@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
}

Some notes:一些注意事项:
from javadoc of @EmbeddedId来自@EmbeddedId的javadoc

There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation is used.使用EmbeddedId注解时, EmbeddedId注解必须只有一个且没有Id注解。

from Java Persistence with Hibernate来自Java 持久性与 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.缺点是管理中间实体实例以创建和删除链接所需的代码更复杂,您必须独立保存和删除这些链接。

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

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