问题
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