JPA:实体随实体扩展

时间:2016-01-28 04:08:42

标签: jpa java-persistence-api

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

@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

2 个答案:

答案 0 :(得分:1)

  • 将@Inheritance注释添加到超类
  • 实施Serializable
  • 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 {

}