1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.