org.hibernate.MappingException:无法确定类型:(foo)

org.hibernate.MappingException: Could not determine type for: (foo)

我有两个 类 由 Hibernate 管理,ClassAClassBClassA 引用了 ClassB。根据文档,Hibernate 应该能够通过反射获取类型。我不明白为什么这不起作用。我在这里错过了一些真正基本的东西吗?

这是 ClassA,标有 @Entity 注释并引用了 ClassB

package dom;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class ClassA {

    private ClassB classB;

    private long id;        

    public ClassA() {};

    public ClassB getClassB() {
        return classB;
    }

    public void setClassB(ClassB classB) {
        this.classB = classB;
    }

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

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

}

这是用 @Enity 注释标记的 ClassB

package dom;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class ClassB {

    private long id;

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

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

}

我得到以下堆栈跟踪:

Caused by: org.hibernate.MappingException: Could not determine type for: dom.ClassB, at table: ClassA, for columns: [org.hibernate.mapping.Column(classB)]
        at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:316)
        at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:294)
        at org.hibernate.mapping.Property.isValid(Property.java:238)
        at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:469)
        at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
        at org.hibernate.cfg.Configuration.validate(Configuration.java:1294)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1742)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1788)
        at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:247)
        at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:373)
        at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:358)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)

您需要用 @OneToOne 注释该字段(假设它不是 @ManyToOne,即许多 ClassB 可以包含许多 ClassA)注释:

@OneToOne
private ClassB classB;

这应该是正确添加实体之间关系所需的最少代码。