如何将实体扩展到另一个实体,但它们都引用同一个表?可能吗 ?结构是这样的:
@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
}
我试过这种方式Extend JPA entity to add attributes and logic
但我得到了这个例外
org.hibernate.mapping.SingleTableSubclass cannot be cast to org.hibernate.mapping.RootClass
更新1
我已将@Id
放入SubUser,因为@Entity
显示此异常
The entity has no primary key attribute defined
答案 0 :(得分:1)
id
添加一个getter(你不一定需要一个setter)id
应为Integer,而不是int,以便您可以使用null表示未分配的ID。 代码:
@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 {
}
答案 1 :(得分:0)
任何基本的JPA文档都会描述继承,鉴别器和@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 {
}