@MappedSuperclass和@OneToMany

Lan*_*erX 4 java annotations hibernate one-to-many mappedsuperclass

UML图

我需要从Country到Superclass Place(@MappedSuperclass)的OneToMany关联.它可以是双向的.我需要像@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;
}
}
Run Code Online (Sandbox Code Playgroud)

国家:

@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
Run Code Online (Sandbox Code Playgroud)

没有@JoinColunm就有例外

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

在表中,City和Region是表Country(Region.country_id,City.country_id)的外键,这是正常的.但我不需要表Country和表Region和City中的外键所以我不需要@JoinColum.

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

axt*_*avt 5

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

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

  • 不过,数据库模式有一个微妙但重要的区别。使用“@MappedSuperclass”,“Place”的每个具体子类都可以有自己的 ID 生成器,而使用“@Inheritance(InheritanceType.TABLE_PER_CLASS)”,它们都必须具有相同的 ID 生成器。例如,“Place”的两个不同子类型的实例在前一种情况下可以具有相同的 ID 号,但在后一种情况下则不能。 (2认同)