简体   繁体   English

Java Hibernate如何使用注释映射继承

[英]Java hibernate how to map Inheritance using annotations

How can i map inheritance class in Hibernate : 如何在Hibernate中映射继承类:

For example i have abstract class figure and two child classes Square and Circle. 例如,我有抽象类图和两个子类Square和Circle。 How can i map them all to be in one table, for example "figures" ? 我如何将它们全部映射到一个表中,例如“图”?

I have tried something like this 我已经尝试过这样的事情

@Entity
@Table(name = "figures")
public abstract Figure{
}

@Entity
@Table(name = "figures")
public class Square extends Figure{

}

@Entity
@Table(name = "figures")
public class Circle extends Figure{

}

but it doesnt work. 但它不起作用。

Thanks for any help :) 谢谢你的帮助 :)

What you need to do is add annotations to parent class : 您需要做的是向父类添加注释:

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING)
@Table(name = "figures")

DiscriminatorColumn will be a new column created by hibernate to know what type this object is. DiscriminatorColumn将是由hibernate创建的新列,用于了解此对象的类型。

In my case I create a column with name "type" 就我而言,我创建了一个名称为“ type”的列

And also annotations to all your child class 以及所有子类的注释

In DiscriminatorValue you need to insert a value that hibernate use to identify that class 在DiscriminatorValue中,您需要插入一个用于休眠的值以标识该类

In my case it is String. 就我而言,它是字符串。 (discriminatorType in DiscriminatorColumn annotations) (DiscriminatorColumn批注中的discriminatorType)

@Entity
@DiscriminatorValue(V)

so in your case it could look like that : 所以在您的情况下,它看起来可能像这样:

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING)
@Table(name = "figures")
public class Figure{

}

@Entity
@DiscriminatorValue("S")
public class Square extends Figure{

}

@Entity
@DiscriminatorValue("C")
public class Circle extends Figure{

}

You can find more info here : http://www.javatpoint.com/hibernate-table-per-hierarchy-using-annotation-tutorial-example 您可以在此处找到更多信息: http : //www.javatpoint.com/hibernate-table-per-hierarchy-using-annotation-tutorial-example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM