mat mat - 1 month ago 7
Java Question

Java hibernate how to map Inheritance using annotations

How can i map inheritance class in Hibernate :

For example i have abstract class figure and two child classes Square and 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 :)

Answer

what you need to do is add annotations to parrent class :

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

DiscriminatorColumn will be a new collumn creted by hibernate to know what type this object is. In my case i create a collumn with name "type"

and also annotations to all your child class In DiscriminatorValue you need to insert a value that hibernate use to identify that class in my case it is String. (discriminatorType in DiscriminatorColumn annotations)

@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

Comments