java - @MappedSuperclass 和@OneToMany

标签 java hibernate annotations one-to-many mappedsuperclass

我需要关联 @OneToMany 从 Country 到父类(super class) 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 会有一个异常(exception):

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

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

我能做什么?

最佳答案

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

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

关于java - @MappedSuperclass 和@OneToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4769546/

相关文章:

java - 存储字符串格式的实用方法

java - 如何使用 Open SAML 签署 SAML 响应?

java - 指定单向 @OneToOne JPA 映射的所有者

java - 方法注释和默认访问级别的奇怪行为

java - 为什么在Controller注解中使用@Component

java - Spring Neo4j 保存 MultipartFile

java - 在liferay中上传带有元数据的文档

java - Wicket:如何处理长时间运行的任务

java - JPA EJB PersistenceContext 没有注入(inject) EntityManager

android - Unresolved reference : Parcelize after adding necessary tools in gradle and updating to kotlin latest version