【问题标题】:@MappedSuperclass and @OneToMany@MappedSuperclass 和 @OneToMany
【发布时间】:2011-06-13 18:18:12
【问题描述】:

我需要将 Country 的 @OneToMany 关联到超类 Place (@MappedSuperclass)。它可以是双向的。我需要像@OneToAny 这样的东西。

@MappedSuperclass
public class Place {

    private String name;
    private Country country;

    @Column
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ManyToOne
    @JoinColumn(name="country_id")
    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }
}

国家:

@Entity
   public class Country {
   private long id;
   private String name;
   private List<Place> places;

   @Any(metaColumn = @Column(name = "place_type"), fetch = FetchType.EAGER)
   @AnyMetaDef(idType = "integer", metaType = "string", metaValues = {
         @MetaValue(value = "C", targetEntity = City.class),
         @MetaValue(value = "R", targetEntity = Region.class) })
   @Cascade({ org.hibernate.annotations.CascadeType.ALL })
   //@JoinColumn(name="unnecessary") 
   //@OneToMany(mappedBy="country")  // if this, NullPointerException...
   public List<Place> getPlaces() {
      return places;
   }
//and rest of class

没有@JoinColunm有一个例外:

原因:org.hibernate.AnnotationException:@Any 需要明确的@JoinColumn(s):tour.spring.bc.model.vo.Country.places

在表 City 和 Region 是表 Country (Region.country_id, City.country_id) 的外键,这没关系。 但我不需要表 Country 到表 Region 和 City 中的外键,所以我不需要 @JoinColum

我能做什么?

【问题讨论】:

    标签: java hibernate annotations one-to-many mappedsuperclass


    【解决方案1】:

    @Any 在这里没有意义,因为外键位于Places 一侧,因此不需要额外的元列。

    我不确定是否可以创建与@MappedSuperclass 的多态关系。但是,您可以尝试将Place 声明为@Entity @Inheritance(InheritanceType.TABLE_PER_CLASS),它应该产生相同的数据库架构并允许多态关系。

    【讨论】:

    • 虽然在数据库模式中有一个微妙但重要的区别。对于@MappedSuperclassPlace 的每个具体子类都可以有自己的 ID 生成器,而对于 @Inheritance(InheritanceType.TABLE_PER_CLASS),它们都必须具有相同的 ID 生成器。例如,Place 的两个不同子类型的实例在前一种情况下可以具有相同的 ID 号,但在后一种情况下则不能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多