开发者

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

开发者 https://www.devze.com 2023-02-19 14:07 出处:网络
I\'m trying to map a USER/FRIEND relation ships using JPA over Hibernate. The ralation ship have an extra coloumn friendShipStatu开发者_开发知识库s that describe if the requested frien has accepted on

I'm trying to map a USER/FRIEND relation ships using JPA over Hibernate. The ralation ship have an extra coloumn friendShipStatu开发者_开发知识库s 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.


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>();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号