How to map a ManyToMany reflexive relations ship with extra coloumn in JPA

会有一股神秘感。 提交于 2019-12-14 03:08:48

问题


I'm trying to map a USER/FRIEND relation ships using JPA over Hibernate. The ralation ship have an extra coloumn friendShipStatus that describe if the requested frien has accepted on not the friendship request. This is the data base model that i want to get by the mapping.

User
=====
Id
Name
etc...

UserFriend
===========
UserId ( foreign key --> user_id)
FriendId ( foreign key --> user_id)
userFriendStatus
FriendShipRequestDate

I also need an exemple of code using this relationShips.


回答1:


Since you have additional columns in the join table, it can't be mapped using a ManyToMany. It must be mapped as two OneToMany relationships :

One User (source) has many Friendships

One Friendship is for one source User (the user who asked for friendship)

One Friendship is for one target User (the user who must accept the friendship)

You should thus have the following entities :

@Entity
public class User {
    // ...
    /**
     * the list of friendships asked by this user
     */
    @OneToMany(mappedBy = "sourceUser")
    private List<Friensdship> frienships = new ArrayList<Friendship>();

}

@Entity
public class Friendship {
    // ...
    /**
     * the user who asked the friendship
     */
    @ManyToOne()
    @JoinColumn(name = "user_id")
    private User sourceUser;

    /**
     * the user to whom the friendship was asked
     */
    @ManyToOne()
    @JoinColumn(name = "friend_id")
    private User targetUser;
}

If needed, you may also ad the reverse relationship in the user :

/**
 * the list of friendships asked to this user
 */
@OneToMany(mappedBy = "targetUser")
private List<Friendship> requestedFriendships = new ArrayList<Friendship>();


来源:https://stackoverflow.com/questions/5434253/how-to-map-a-manytomany-reflexive-relations-ship-with-extra-coloumn-in-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!