Hibernate问题 - "使用@OneToMany或@ManyToMany定位未映射的类"

C0d*_*ack 98 hibernate jpa

我找到了Hibernate Annotations的脚,我遇到了一个问题,我希望有人可以提供帮助.

我有2个实体,Section和ScopeTopic.Section有一个List类成员,所以一对多关系.当我运行我的单元测试时,我得到了这个异常:

使用@OneToMany或@ManyToMany定位未映射的类:com.xxx.domain.Section.scopeTopic [com.xxx.domain.ScopeTopic]

我会假设错误意味着我的ScopeTopic实体未映射到表?我看不到我做错了.以下是实体类:


@Entity
public class Section {
    private Long id;
    private List<ScopeTopic> scopeTopics;

    public Section() {}

    @Id
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @OneToMany
    @JoinTable(name = "section_scope", joinColumns = {@JoinColumn(name="section_id")},
               inverseJoinColumns = {@JoinColumn(name="scope_topic_id")} )
    public List<ScopeTopic> getScopeTopic() {
        return scopeTopic;
    }

    public void setScopeTopic(List<ScopeTopic> scopeTopic) {
        this.scopeTopic = scopeTopic;
    }
}
Run Code Online (Sandbox Code Playgroud)
@Entity
@Table(name = "scope_topic")
public class ScopeTopic {
    private Long id;
    private String topic;

    public ScopeTopic() {}

    @Id
    public Long getId() {
        return id;
    }

    public void setId() {
        this.id = id;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }
}
Run Code Online (Sandbox Code Playgroud)

我很确定这是我自己缺乏理解,这是错误的,所以一些指导会很棒,谢谢!

Boz*_*zho 227

你的注释看起来很好.以下是要检查的内容:

  • 确保注释是javax.persistence.Entity,而不是org.hibernate.annotations.Entity.前者使实体可检测.后者只是一个补充.

  • 如果您手动列出实体(在persistence.xml中,在hibernate.cfg.xml中,或在配置会话工厂时),请确保您还列出了ScopeTopic实体

  • 确保您ScopeTopic在不同的包中没有多个类,并且导入了错误的类.

  • 啊,谢谢!第2点是关键,在创建SessionFactory时,我忘记将ScopeTopic放入我的annotatedClasses属性列表中,n00b错误! (15认同)
  • 对于那些刚刚发表评论的人.org.hibernate.annotations.Entity在Hibernate 4中已弃用.第1点不再适用. (3认同)

You*_*ans 22

@Entity的多方实体并没有

@Entity // this was commented
@Table(name = "some_table")
public class ChildEntity {
    @JoinColumn(name = "parent", referencedColumnName = "id")
    @ManyToOne
    private ParentEntity parentEntity;
}
Run Code Online (Sandbox Code Playgroud)


c.s*_*ala 19

您的实体可能未在hibernate配置文件中列出.


Sai*_*eek 5

大多数情况下Hibernate,需要添加类似的Entityhibernate.cfg.xml-

<hibernate-configuration>
  <session-factory>

    ....
    <mapping class="xxx.xxx.yourEntityName"/>
 </session-factory>
</hibernate-configuration>
Run Code Online (Sandbox Code Playgroud)


VLa*_*ova 5

SessionFactory就我而言,在构建 时,我必须添加我的类addAnnotationClass

Configuration configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration
            .addAnnotatedClass(MyEntity1.class)
            .addAnnotatedClass(MyEntity2.class)
            .buildSessionFactory(builder.build());
Run Code Online (Sandbox Code Playgroud)