如何在JPA中用额外的语言映射ManyToMany自反关系船 [英] How to map a ManyToMany reflexive relations ship with extra coloumn in JPA

查看:228
本文介绍了如何在JPA中用额外的语言映射ManyToMany自反关系船的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Hibernate上使用JPA映射USER/FRIEND关系.礼节船还有一个额外的FriendShipStatus,用于描述所请求的朋友是否已接受而非友谊请求. 这是我想通过映射获取的数据库模型.

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

我还需要一个示例代码来使用此RelationshipShips.

I also need an exemple of code using this relationShips.

推荐答案

由于联接表中还有其他列,因此无法使用ManyToMany对其进行映射.它必须映射为两个OneToMany关系:

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

这篇关于如何在JPA中用额外的语言映射ManyToMany自反关系船的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆