Reputation: 29673
Let's I have table
USER
-id : long
-login : varchar
-weapon: varchar
-magic: varchar
And I want map this Table on two classes (using Hibernate/JPA)
class Mag
{
long id;
String login;
String weapon;
}
and
class Warrior
{
long id;
String login;
String magic;
}
And if I send HQL query : SELECT m FROM Mag m WHERE m.login = ?
then I get Mag instance
and if I send HQL query : SELECT w FROM Warrior w WHERE w.login = ?
then I get Warrior instance
I try make something like this
@Entity
@Table(name = "User")
class User
{
long id;
String login;
}
@Entity
class Mag extends User
{
String magic;
}
@Entity
class Warrior extends User
{
String weapon;
}
But @Inheritance requared discriminator column, but I haven't discriminator.
Upvotes: 5
Views: 6851
Reputation: 716
You can use the Discriminator for this,if you have a deliminator column. Assume you deliminator column is
utype char(1)
And if
utype = m, that is a Mag entity and
utype=w, that is Warrior entity
Please find code bellow.
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "utype", discriminatorType = DiscriminatorType.CHAR)
@Table(name = "User")
class User
{
long id;
String login;
}
@Entity
@DiscriminatorValue("m")
class Mag extends User
{
String magic;
}
@Entity
@DiscriminatorValue("w")
class Warrior extends User
{
String weapon;
}
Upvotes: 2
Reputation: 20270
You're looking for MappedSuperClass, which allows the subclasses to inherit the annotations from the superclass without needing a discriminator.
Upvotes: 8