2011-01-22 39 views
4

UML Diagram@MappedSuperclass和@OneToMany

我需要一对多协会从国家到地方超类(@MappedSuperclass)。它可以是双向的。我wolud需要像@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有例外

Caused by: org.hibernate.AnnotationException: @Any requires an explicit @JoinColumn(s): tour.spring.bc.model.vo.Country.places 

在表城市和地区为外键表国家(Region.country_id,City.country_id)没问题。 但我不需要在表Country和Country中的外键,所以我不需要@JoinColum。

我一直在寻找解决方案,但似乎没有很好的解决方案。

回答

5

@Any在这里没有意义,因为外键是在Place的一边,因此它不需要额外的元列。

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

+0

尽管数据库模式存在细微但重要的差异。对于`@ MappedSuperclass`,`Place`的每个具体子类都可以拥有自己的ID生成器,而使用`@Inheritance(InheritanceType.TABLE_PER_CLASS)`,它们都必须具有相同的ID。例如,两个不同的`Place`子类型的实例在前一种情况下可以具有相同的ID号,但在后一种情况下它们不能。 – Devaro 2018-01-17 10:23:38