【问题标题】:Hibernate inheritance - no field annotated with IdHibernate 继承 - 没有用 Id 注释的字段
【发布时间】:2014-07-29 21:41:30
【问题描述】:

我一直在阅读有关休眠继承的一些内容,但在将其应用于我的情况时遇到了麻烦。 I tried doing what this post mentioned which seems like it should be what I want.

这是我正在使用的 3 个类 - 每个类都应该有自己的表:

  • 父类
    • 子类
  • 分离表

下面基本上是我已经列出的内容。但是,当我尝试在 Child 类服务上运行测试时,它们都因java.lang.IllegalStateException: no field annotated with Id 而失败。现在,如果我正确理解了那篇文章/博客文章,我应该不需要用 Id 注释的 ChildClass,因为它应该在父类中获取。

我可能完全错了,因为我是 Hibernate 的新手,但如果你们有任何想法,我很高兴听到我做错了什么。

父类

@Table(name="parent_class")
@Inheritance(strategy=InheritanceType.JOINED)
public class ParentClass {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long m_id;

@Column(nullable=false, length=2500)
private String m_variable;

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="s_key", nullable=false)
private SeparateTable m_sTable;

etc...
}

子类

@Table(name="child_class")
@PrimaryKeyJoinColumn(name="m_id")
public class ChildClass extends ParentClass {

@Column(nullable=false, length=100)
private String m_name;

@Column(nullable=true, length=250)
private String m_description;

etc...
}

分离表

@Table(name="separate_table")
public class SeparateTable {

@Id
@Column(unique=true, nullable=false, length=100)
private String m_user;

@OneToMany(mappedBy="m_sTable", cascade={CascadeType.ALL}, fetch=FetchType.LAZY, orphanRemoval=true)
private Set<ParentClass> m_parents;

@OneToMany(mappedBy="m_sTable", cascade={CascadeType.ALL}, fetch=FetchType.LAZY, orphanRemoval=true, targetEntity=ParentClass.class)
private Set<ChildClass> m_children;

etc...
}

【问题讨论】:

  • 我猜你只是省略了@javax.persistence.Entity 注释?
  • 这可能无法解决您的问题,但 ParentClass 应该是抽象的,特别是如果您不想使用该类创建实体。然后应该用@MappedSuperclass 注释这个父类。如果父类是常规实体,Hibernate 有时会出现从代理对象获取正确实体类型的问题。我想有一些 SO 问题提到了这个问题。
  • @Wolfram - 当这两个类都被分离出来(每个类中都有重复的变量)时,我所需要的只是@Table,我没有任何问题。因此,为了回答您的问题,我从未使用过 @javax.persistence.Entity 注释。
  • @Tom - 我以前见过@MappedSuperclass,但当它适用时我不是100%。我确实想用父类和子类创建实体。编辑:我收回了,汤姆。阅读文档后,我阅读:A mapped superclass has no separate table defined for it. 这表明它不适用于我的情况。

标签: java hibernate inheritance h2


【解决方案1】:

将m_id的作用域改为protected

protected Long m_id;

【讨论】:

    【解决方案2】:

    事实证明,我们的一个 util 类正在为每个扩展抽象 Hibernate 类的类寻找 Id 字段。由于子类没有 @Id 注释,所以它被炸毁了。

    所需要的只是添加一个简单的检查以查看是否有父类,如果有,则从那里获取带注释的字段。

    【讨论】:

      猜你喜欢
      • 2015-05-27
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 2014-10-05
      相关资源
      最近更新 更多