tags:

views:

596

answers:

3

I have a some JPA entities that inherit from one another and uses discriminator to determine what class to be created (untested as of yet).

@Entity(name="switches")
@DiscriminatorColumn(name="type")
@DiscriminatorValue(value="500")
public class DmsSwitch extends Switch implements Serializable {}

@MappedSuperclass
public abstract class Switch implements ISwitch {}

@Entity(name="switch_accounts")
public class SwitchAccounts implements Serializable {
    @ManyToOne()
    @JoinColumn(name="switch_id")
    DmsSwitch _switch;
}

So in the SwitchAccounts class I would like to use the base class Switch because I don't know which object will be created until runtime. How can I achieve this?

A: 

I don't think that you can with your current object model. The Switch class is not an entity, therefore it can't be used in relationships. The @MappedSuperclass annotation is for convenience rather than for writing polymorphic entities. There is no database table associated with the Switch class.

You'll either have to make Switch an entity, or change things in some other way so that you have a common superclass that is an entity.

Dan Dyer
A: 

As your switch class is not an entity, it cannot be used in an entity relationship... Unfortunately, you'll have to transform your mappedsuperclass as an entity to involve it in a relationship.

Nicolas
+1  A: 

As the previous commentors I agree that the class model should be different. I think something like the following would suffice:

@Entity(name="switches")
@DiscriminatorColumn(name="type")
@DiscriminatorValue(value="400")
public class Switch implements ISwitch {
  // Implementation details
}

@Entity(name="switches")
@DiscriminatorValue(value="500")
public class DmsSwitch extends Switch implements Serializable {
  // implementation
}

@Entity(name="switches")
@DiscriminatorValue(value="600")
public class SomeOtherSwitch extends Switch implements Serializable {
  // implementation
}

You could possibly prevent instantiation of a Switch directly by making the constructor protected. I believe Hibernate accepts that.

extraneon