Reputation: 727
How can I extend an entity with another entity but both of them referring to the same table ? Is it possible ? The structure is something like this :
@Entity
@Table(name = "users")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable{
private int id;
private String name;
}
@Entity
@Table(name = "users")
@NamedQuery(name="SubUser.findAll", query="SELECT su FROM SubUser su")
public class SubUser extends User {
@Override
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return super.getId();
}
//- Other fields and getter setter
}
I tried this way Extend JPA entity to add attributes and logic
but I got this exception
org.hibernate.mapping.SingleTableSubclass cannot be cast to org.hibernate.mapping.RootClass
Update 1
I already put the @Id
for the SubUser because the @Entity
shows this exception
The entity has no primary key attribute defined
Upvotes: 1
Views: 7442
Reputation: 48256
id
(you don't need a setter necessarily)id
should be Integer, not int, so that you can represent unassigned ids with null. Code:
@Entity
@Table(name = "users")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
public class SubUser extends User {
}
Upvotes: 2
Reputation: 11531
Any basic JPA docs would describe inheritance, discriminators and use of @Id
.
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="DISCRIM", discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue("User")
@Table(name="users")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
}
@Entity
@DiscriminatorValue("SubUser")
@NamedQuery(name="SubUser.findAll", query="SELECT su FROM SubUser su")
public class SubUser extends User {
}
Upvotes: -1