Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discriminator in InheritanceType.JOINED

Tags:

Is it possible to force hibernate to use discriminator column for inheritance type joined? According to JPA2.0 specification this should be possible but i can't achieve it in hibernate.

Example:

@Inheritance(strategy = InheritanceType.JOINED)
@ForceDiscriminator
@DiscriminatorColumn(name="TYPE")
@Entity
public class Parent

@Entity
@DiscriminatorValue("C")
public class Child extends Parent

This doesn't even create column TYPE in the table PARENT when using hibernate.hbm2ddl.auto create.

I know that InheritanceType.JOINED works without defining discriminator column but it's quite ineffective because then hibernate needs to create joins between parent and all children instead of just parent and one child when using information in discriminator column.

like image 990
milbr Avatar asked Nov 25 '10 09:11

milbr


People also ask

What is discriminator in JPA?

The discriminator column is always in the table of the base entity. It holds a different value for records of each class, allowing the JPA runtime to determine what class of object each row represents. The DiscriminatorColumn annotation represents a discriminator column.

What is discriminator value in hibernate?

Discriminator Values. Since the records for all entities will be in the same table, Hibernate needs a way to differentiate between them. By default, this is done through a discriminator column called DTYPE that has the name of the entity as a value.

Is a mapping requires discriminator column?

The SINGLE_TABLE strategy maps records from the same database table to different entity classes of an inheritance hierarchy. If you want to use this strategy with JPA, your database table needs to have a discriminator column. The value in this column identifies the entity class to which each record shall be mapped.

What is discriminator value?

javax.persistence @Target(value=TYPE) @Retention(value=RUNTIME) public @interface DiscriminatorValue. Is used to specify the value of the discriminator column for entities of the given type. The DiscriminatorValue annotation can only be specified on a concrete entity class.


1 Answers

I've used SINGLE_TABLE with a Discriminator and a SecondaryTable on the subclass to do this very thing. I.E.

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE")
@Entity
public class Parent

@Entity
@DiscriminatorValue("C")
@SecondaryTable(name = "child", pkJoinColumns = {@PrimaryKeyJoinColumn(name="id", referencedColumnName = "id")})
public class Child extends Parent

When you add a new sub class you add a new table with the relevant extended data fields in it.

like image 78
BadgerB Avatar answered Sep 30 '22 00:09

BadgerB