JPA:实体随实体扩展 [英] JPA : Entity extend with entity

查看:85
本文介绍了JPA:实体随实体扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

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

但是我遇到了这个异常

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

更新1

我已经为子用户放置了@Id,因为@Entity显示了此异常

I already put the @Id for the SubUser because the @Entity shows this exception

The entity has no primary key attribute defined

推荐答案

  • 将@Inheritance注释添加到超类
  • 实现可序列化
  • id添加一个吸气剂(您不一定需要一个setter)
  • id应该是Integer,而不是int,以便您可以用null表示未分配的ID.
    • Add the @Inheritance annotation to the super class
    • Implement Serializable
    • Add a getter for id (you don't need a setter necessarily)
    • id should be Integer, not int, so that you can represent unassigned ids with null.
    • 代码:

      @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 {
      
      }
      

      这篇关于JPA:实体随实体扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆