简体   繁体   中英

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. 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. should be 2

I've tried quite a few other configurations, including adding a "referencedColumnName" attribute to each @JoinColumn, but they have also yielded errors. 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引用发生冲突。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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