简体   繁体   English

JPA-使用中间表在同一张表之间映射OneToMany关联

[英]JPA - Mapping OneToMany association between the same table using an intermediate table

I'm creating an application where one large aspect is the ability for users to share content with friends. 我正在创建一个应用程序,其中一个很大的方面是用户与朋友共享内容的能力。 I'm trying to represent this in the object model and I'm having trouble getting the association to work properly. 我试图在对象模型中表示这一点,但在使关联正常工作方面遇到困难。 I'm using a mapping table that records the friender and the friendee, both of which are represented by the primary key (id) of the user. 我使用的映射表记录了Friender和Friendee,两者均由用户的主键(id)表示。 A user can have many friends, and also be referenced by other users. 一个用户可以有很多朋友,也可以被其他用户引用。 This is what the schema looks like: 架构如下所示:

Users:
int user_id (PK)
varchar(32) email
varchar(64) password

Users_Map:
int users_map_id (PK)
int friendee_id (FK references users(user_id))
int friender_id (FK references users(user_id))

And this is how I have the User entity set up: 这就是我设置用户实体的方式:

@Data
@Entity
@Table(name = "users")
public class User extends AbstractPersistable<Long> {

    @Id
    @Column(name = "user_id")
    private Long id;

    @Column
    private String email;

    @Column
    private String password;

    @OneToMany
    @JoinTable(name = "users_map",
            joinColumns = { @JoinColumn(name = "friender_id") },
            inverseJoinColumns = { @JoinColumn(name = "friendee_id") })
    private List<User> friends;
}

I run into the following error when deploying the application: 部署应用程序时遇到以下错误:

org.hibernate.AnnotationException: A Foreign key refering com.x.webapp.data.entity.User from com.x.webapp.data.entity.User has the wrong number of column. org.hibernate.AnnotationException:从com.x.webapp.data.entity.User引用com.x.webapp.data.entity.User的外键具有错误的列数。 should be 2 应该是2

I've tried quite a few other configurations, including adding a "referencedColumnName" attribute to each @JoinColumn, but they have also yielded errors. 我尝试了很多其他配置,包括向每个@JoinColumn添加“ referencedColumnName”属性,但是它们也产生了错误。 I'm also not entirely sure whether the schema I currently have is the best way to go about mapping users together. 我也不完全确定当前拥有的架构是否是将用户映射到一起的最佳方法。

I appreciate any help! 感谢您的帮助!

删除AbstractPersistable的扩展名解决了该问题-包含一个@Id引用,并与我放入User内部的@Id引用发生冲突。

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

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