何时在 hibernate 中使用 DiscriminatorValue 注释 [英] When to use DiscriminatorValue annotation in hibernate

查看:34
本文介绍了何时在 hibernate 中使用 DiscriminatorValue 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 hibernate 中使用 DiscriminatorValue 注释的最佳场景是什么以及什么时候?

What and when is the best scenario to use DiscriminatorValue annotation in hibernate?

推荐答案

这2个链接最能帮助我理解继承概念:

These 2 links help me understand the inheritance concept the most:

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

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

要了解判别器,首先要了解继承策略:SINGLE_TABLE、JOINED、TABLE_PER_CLASS.

To understand discriminator, first you must understand the inheritance strategies: SINGLE_TABLE, JOINED, TABLE_PER_CLASS.

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

Discriminator is commonly used in SINGLE_TABLE inheritance because you need a column to identify the type of the record.

示例:您有一个 Student 类和 2 个子类:GoodStudent 和 BadStudent.Good 和 BadStudent 数据都将存储在 1 个表中,但当然我们需要知道类型,这就是 (DiscriminatorColumn 和) DiscriminatorValue 的时候.

Example: You have a class Student and 2 sub-classes: GoodStudent and BadStudent. Both Good and BadStudent data will be stored in 1 table, but of course we need to know the type and that's when (DiscriminatorColumn and) DiscriminatorValue will come in.

注释学生类

@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 的列,并将在其中保存学生的 DiscriminatorValue.

So now the Student table will have a column named Student_Type and will save the DiscriminatorValue of the Student inside it.

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

查看我上面发布的链接.

See the links I posted above.

这篇关于何时在 hibernate 中使用 DiscriminatorValue 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆