Hibernate @ManyToOne引用了一个未知实体

use*_*368 43 java hibernate jpa

我收到以下Hibernate异常:

@OneToOne or @ManyToOne on Matchup.awayTeam references an unknown entity: Team

简化的Matchup类如下所示:

@Entity public class Matchup implements Serializable 
{
   protected Team awayTeam;

   @ManyToOne 
   @JoinColumn(name="away_team_id")
   public Team getAwayTeam() {
      return awayTeam;
   }
}
Run Code Online (Sandbox Code Playgroud)

简化的Team类看起来像这样:

@Entity
public class Team implements Serializable {
    protected List<Matchup> matchups;

    @OneToMany(mappedBy="awayTeam", targetEntity = Matchup.class,
    fetch=FetchType.EAGER, cascade=CascadeType.ALL)
    public List<Matchup> getMatchups() {
       return matchups;
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • Matchup和Team都有子类.我不确定这是否会影响这种情况.
  • Matchup和Team都列在我的persistence.xml中作为包含.
  • 如果我在两个getter方法上放置@Transient注释,则错误消失.

任何人都可以阐明为什么会发生这种异常吗?

use*_*368 64

我想出了问题:我没有将类Team添加到Hibernate AnnotationConfiguration对象中.因此,Hibernate没有认识到这个类.

  • 在我的情况下,我在一个类中忘记了@entity Annotation,并且我收到了与您相同的错误消息.我只发布这个信息,如果有人和我做同样的(愚蠢的)bug :-) (7认同)
  • 你能描述一下如何将类Team添加到Hibernate AnnotationConfiguration对象中吗? (6认同)
  • 我认为他的意思是在@ManyToOne(targetEntity= Team.class) 中添加targetEntity (2认同)

Dha*_*l D 20

除了在hibernate.cfg.xml中输入外,您还需要@Entity在引用的类上进行注释.


bvd*_*vdb 10

如果您将 Spring Boot 与 hibernate 结合使用,那么实际上您可能只需要将该包添加到您的@EntityScan基础包数组中即可。

@SpringBootApplication(scanBasePackages = {"com.domain.foo.bar.*"})
@EnableJpaRepositories(basePackages ={"com.domain.foo.bar.*"})
@EntityScan(basePackages ={"com.domain.foo.bar.*", "com.domain.another.*"})
public class SpringBootApplication extends SpringBootServletInitializer {
}
Run Code Online (Sandbox Code Playgroud)


小智 6

另一个解决方案:检查以确保所引用的类包含在hibernate.cfg.xml文件中。