简体   繁体   中英

Self referencing Entity in Hibernate with additional Columns

I wanna map these tables with Hibernate:

CREATE TABLE user
(
    id VARCHAR(20), 
    //some stuff    
    PRIMARY KEY(id)


);

CREATE TABLE friendship
(
    user1 VARCHAR(20),
    user2 VARCHAR(20),
    firstMeeting TIMESTAMP,
    //mb some additional stuff
    PRIMARY KEY(user1, user2),
    FOREIGN KEY(user1) REFERENCES user(id),
    FOREIGN KEY(user2) REFERENCES user(id)
);

I wonder about the right way to map this. I thought about this:

User entity with

@ManyToMany Set<Friendship> friendships;

Friendship entitiy with

@Size(min=2, max=2)
@ManyToMany Set<User> members;

Date firstMeeting;

BUT i dont think this matches the schema above (not only in column names but in tbl count, the schema needs 2 but this would need 3 tables mapped to, the 2 entities and 1 for the ManyToMany relationship mapping table). The problm is i cant map this as 2times

@ManyToOne User user1/2;

because then i wont be able to redirect a friendship from a user, BECAUSE i cant add something like

@OneToMany Set<Friendship> friendships; 

to user because i wont be able to specify the mappedBy=? argument, so the relationship would be mapped in a additional table...

BUT i want to keep it bidirectional.

Any good solution for this problem?

Besides it doesnt matter how the users are ordered in the friendship table, so (user1, user2) = (user2, user1). I think this would be best expressed in an idClass/EmbeddedId with an equivalent equals()-Implementation, right?

EDIT: It seems to be possible to archieve this, if u define some order over the 2 elements, like from<->to, owner<->owned, but i dont see any natural order in this relation and i dont rly want to define some artificial stuff just for this technical issue ...

User entity with

@ManyToMany Set<Friendship> friendships;

and then friendship table :

User member;
User memberFriend;
Date firstMeeting;

or if you want Friendship entitiy with PRIMARY KEY(user1, user2), the entity must be split to 2 table like :

FriendFK fKey;
Date firstMeeting;

and table FriendFK :

User member;
User memberFriend;

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