ManyToMany在同一个实体上使用MappedSuperclass中的字段

时间:2018-01-12 20:23:29

标签: java hibernate spring-mvc

我想在两侧创建与ManyToMany关系相同的表。它应该代表两个用户之间的友谊。我现在有用户类:

@Entity
@Table(name = "Users")
public class User extends BaseObject implements UserDetails {

    //example of others relationship
    private Set<Post> posts;

     @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true
        , mappedBy = "author")
    @OrderBy("dateOfCreation DESC")
    public Set<Post> getPosts() {
        return posts;
    }

    public void setPosts(Set<Post> posts) {
        this.posts = posts;
    }
}

@MappedSuperclass

@MappedSuperclass
public class BaseObject {

    /** Object id */
    private Long id;

    @Id
    @GeneratedValue
    public Long getId() {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }
}

因为我想在此关系中添加一些新列,所以我必须创建新的Entity,它将用作连接表。所以我知道UserFriend

@Entity
@Table(name = "UserFriends")
public class UserFriend {

    /** User */
    private User user;
    /** User's friend */
    private User friend;
    /** Pending friendship*/
    private boolean accepted;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public User getFriend() {
        return friend;
    }

    public void setFriend(User friend) {
        this.friend = friend;
    }

    //other getter setter
}

现在我需要连接这些表。我想使用user_idfriend_id指向id实体的User字段。但我不确定如何实现这一目标。你能否告诉我如何使用正确的注释?或者给我更好的方法(例如使用新字段用户)。

1 个答案:

答案 0 :(得分:0)

您可以使用单向/** User */ @ManyToOne @JoinColumn(name = "user_id") private User user; /** User's friend */ @ManyToOne @JoinColumn(name = "friend_id") private User friend; 映射。

UserFriends

Hibernate使用列user_idfriend_id生成表Id。这些列包含映射的超类的create table UserFriends (id bigint not null, accepted boolean not null, friend_id bigint, user_id bigint, primary key (id)) create table Users (id bigint not null, primary key (id)) 引用的连接用户。

快速验证Hibernate生成的DDL语句确认了该功能。

import tkinter.filedialog as filedialog
import os
import pygame

directory = filedialog.askdirectory()
os.chdir(directory)
song_list = []
for file in os.listdir(directory):
    if file.endswith('.mp3'):
         song_list.append(file)
pygame.mixer.init()
pygame.mixer.music.load(song_list[0])
pygame.mixer.music.play()