小编典典

何时在hibernate状态下使用DiscriminatorValue注释

hibernate

什么和何时在hibernate状态下使用DiscriminatorValue注释的最佳方案是什么?


阅读 285

收藏
2020-06-20

共1个答案

小编典典

这两个链接帮助我最了解继承概念:

http://docs.oracle.com/javaee/6/tutorial/doc/bnbqn.html

http://www.javaworld.com/javaworld/jw-01-2008/jw-01-jpa1.html?page=6

要了解区分符,首先您必须了解继承策略:SINGLE_TABLE,JOINED,TABLE_PER_CLASS。

鉴别符通常在SINGLE_TABLE继承中使用,因为您需要一个列来标识记录的类型。

示例:您有一个学生类和两个子类:GoodStudent和BadStudent。Good和BadStudent数据都将存储在1个表中,但是我们当然需要知道类型,然后才是(DiscriminatorColumn和)DiscriminatorValue出现的时间。

注释学生班

@Entity
@Table(name ="Student")
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING,
    name = "Student_Type")
public class Student{
     private int id;
     private String name;
}

坏学生班

@Entity
@DiscriminatorValue("Bad Student")
public class BadStudent extends Student{ 
 //code here
}

优秀学生班

@Entity
@DiscriminatorValue("Good Student")
public class GoodStudent extends Student{ 
//code here
}

因此,现在 Student 表将具有一个名为 Student_Type 的列,并将其中保存Student 的
DiscriminatorValue

-----------------------
id|Student_Type || Name |
--|---------------------|
1 |Good Student || Ravi |
2 |Bad Student  || Sham |
-----------------------

请参阅我上面发布的链接。

2020-06-20