Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have discriminator column on secondary table in jpa

I'm currently struggling with mapping an existing db schema to jpa entities, and among a lot of weirdness, I've become stuck on this problem.

I have two tables, similar to this:

Table 1          Table 2         
|Service     |  |Servicetype     |
|servicetype |  |Servicecategory |
|            |  |                |

Where servicetype in table 1 is a foreign key to service type in table two. However, the services in table 1 have wildly different behaviour based on which category they belong to (while there are 100+ servicetypes, there are only 4 categories) I'd like to be able to be a able to map table 1 to four different entityclasses, based on the category of their service type.

This is what I have so far:

@Entity
@Table(name = "table1")
@DiscriminatorColumn(name = "servicecategory", discriminatorType =         
     discriminatorType.INTEGER)
@DiscriminatorValue("1")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@SecondaryTable(name = "table2",
pkJoinColumns =
 @PrimaryKeyJoinColumn(name = "servicetype", referencedColumnName = 
"servicetype"))
public class AbstractService implements Serializable {
...etc

And 4 classes extending from this, buth with a different discriminatorvalue, Which doesn't work, since eclipselink, which I'm using, tries to lookup the value of servicecategory in table1.

Is it possible to express such a mapping with jpa or should I just do the mapping with "where servicecategory = ?" on each query.

like image 886
vruum Avatar asked Nov 13 '22 18:11

vruum


1 Answers

Please file an enhancement in EclipseLink to add support for this feature. A JPA solution would be to switch the primary table with the secondary table - this might cause problems with insertion order though and foreign keys will be referencing the Servicetype in table2.

An EclipseLink specific solution is to use a customizer to change the table used for the descriminator field. Add the @Customizer tag to the entity and specify a class with a method:

public void customize(ClassDescriptor descriptor) {
    descriptor.getInheritancePolicy().getClassIndicatorField().setTable(
        descriptor.getTable("table2"));
}
like image 128
Chris Avatar answered Nov 15 '22 13:11

Chris