一对一休眠将两个外键映射到同一列?

时间:2019-02-18 11:05:24

标签: java spring hibernate jpa

我有一个表用户,另一个表有两个指向用户ID的列,我该如何映射一个到多个关系而不是仅在那些列中的一个中搜索外键,而是在这两个列中的任何一个中进行联接指向用户。我正在使用Spring和Hibernate和JPA。

用户:

+------------+  
|    id      | 
+------------+
|     1      |
|     2      |
+------------+

游戏:(其中user1和user2代表玩家1和2,并带有userId的外键)

+------------+---------+--------+
|    user1   |  user2  |  game  | 
+------------+---------+---------
|      1     |    4    |   1    |
|      6     |    1    |   2    |
+------------+---------+--------+

仅当用户1在第一列中时,我才设法获取用户1的游戏,但用户1在游戏表第二列中时却未获取游戏。有没有办法使用休眠注释?

@Entity
@Table(name = "users")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.EAGER, orphanRemoval = true)
    @JoinTable(name = "games",joinColumns ={@JoinColumn(name ="first_user", referencedColumnName ="id" )},inverseJoinColumns = @JoinColumn(name ="second_user", referencedColumnName ="id" ))
    private List<Game> games;


@Entity
@Table(name = "games")
public class Game {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "first_user", insertable = false, updatable = false)
    private User firstUser;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "second_user", insertable = false, updatable = false)
    private User secondUser;

0 个答案:

没有答案