arinte
arinte

Reputation: 3728

JPA and inheritance

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?

Upvotes: 1

Views: 1501

Answers (3)

extraneon
extraneon

Reputation: 23950

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.

Upvotes: 2

Nicolas
Nicolas

Reputation: 24759

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.

Upvotes: 1

Dan Dyer
Dan Dyer

Reputation: 54465

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.

Upvotes: 0

Related Questions