Hibernate / JPA映射到基类

时间:2012-07-16 10:41:11

标签: java hibernate jpa orm mapping

考虑以下实体。我打算让Child类引用两个衍生食品类(Local Food或Foreign)中的任何一个。这是一个人为的例子,我的真实域对象非常复杂,因此组合和使用FoodType列不是一个选项,因为Food子类只在少数特征中相似。

@MappedSuperclass
public abstract class Food {

}



@Entity
public class LocalFood extends Food {

private long id;
private String name;
}


@Entity
public class ForeignFood extends Food {

    private long id;
    private String name;
}



@Entity
public class Child {    
private Food food; //Base Class needed here 
@ManyToOne()
public Food getFood() {
    return food;
}
}

Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on                     com.sample.Child.food references an unknown entity: com.sample.Food

也没有使用继承和鉴别器。

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class Food {

private long id; // set , get (Auto gen) 
}

是否可以使这种映射工作?

1 个答案:

答案 0 :(得分:2)

JB Nizet是对的。现在食品类看起来像这样。

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Food {

 private long id;

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

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 public long getId() {
    return id;
 }

}

从子类中删除了id。