1

如何用另一个实体扩展一个实体,但它们都引用同一个表?可能吗 ?结构是这样的:

@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

}

我试过这种方式扩展 JPA 实体以添加属性和逻辑

但我得到了这个例外

org.hibernate.mapping.SingleTableSubclass cannot be cast to org.hibernate.mapping.RootClass

更新 1

我已经@Id为 SubUser 放置了,因为@Entity显示了这个异常

The entity has no primary key attribute defined

4

2 回答 2

2
  • 给超类添加@Inheritance注解
  • 实现可序列化
  • 添加一个getter id(你不一定需要一个setter)
  • id应该是整数,而不是整数,这样您就可以用 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 {

}
于 2016-01-28T04:11:56.830 回答
-1

任何基本的 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 {

}
于 2016-01-28T09:03:51.113 回答