mat
mat

Reputation: 13

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 :)

Upvotes: 1

Views: 720

Answers (1)

Mateusz Mańka
Mateusz Mańka

Reputation: 858

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.

In my case I create a column 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

Upvotes: 2

Related Questions