从两个表创建参考表

时间:2018-09-12 21:49:11

标签: java hibernate java-ee

我将网站转换为使用Java EE并休眠!

我有3张桌子:

like
id | table | idElement | userId

movie
movie_id | title | duration

videoGame
game_id | title | nbPlayer

,目前有2个班级:

@Entity
@Table(name="movie")
public class Movie {

    @Id
    @GeneratedValue
    @Column(name="movie_id")
    private Integer id;
    private String title;
    private int duration;

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

    @Id
    @GeneratedValue
    @Column(name="game_id")
    private Integer id;
    private String title;
    private int nbPlayer;

我不知道如何使我的表“喜欢”以将其链接到两个表之一和正确的ID?

示例:

table like:
+---+-------+-----------+-------+
|id | table | idElement | userId|
|1  | movie |  1        | 1     |
|1  | game  |  5        | 3     |
+---+-------+-----------+-------+

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

似乎没有直接的方法可以将表映射为休眠状态(至少我不知道)。

使用继承可以产生类似的效果。 MovieGame可以是另一个类的子类(例如Likable)。这样您就可以使用Likable类,如下所示:

 @Entity
 @Table(name="like")
 public class Like {

   @Id
   @GeneratedValue
   @Column(name="like_id")
   private Integer id;

   @ManyToOne
   @JoinColumn(name="likable_id", nullable=false)
   private Likable likable;

   @ManyToOne
   @JoinColumn(name="user_id", nullable=false)
   private User user;
}

Likable类如下所示:

@Entity  
@Table(name = "likable")  
@Inheritance(strategy=InheritanceType.JOINED)   
public class Likable {  

   @Id  
   @GeneratedValue(strategy=GenerationType.AUTO)     
   @Column(name = "id")  
   private int id;  

 }

Movie类:

 @Entity
 @Table(name="movie")
 @PrimaryKeyJoinColumn(name="id")  
 public class Movie extends Likable {

     private String title;
    private int duration;
}

Game类:

@Entity
@Table(name="videoGame")
@PrimaryKeyJoinColumn(name="id")
public class Game extends Likable {

   private String title;
   private int nbPlayer;
}