Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

java - When to use DiscriminatorValue annotation in hibernate

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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

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

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.

Annotate Student class

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

Bad Student class

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

Good Student class

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...