我可以在@MappedSuperclass中使用@OneToMany(mappedBy =“ ...”)吗?

时间:2019-08-10 09:07:14

标签: java spring hibernate jpa

最近,我读了article,内容是Vlad Mihalcea与JPA和Hibernate映射@OneToMany关系的最佳方法。我也想为我的类使用所描述的映射,但是我的引用方必须是MappedSuperclass *。

假设我有这两类:

@MappedSuperclass
@AllArgsConstructor
@NoArgsConstructor
@Setter
public abstract class Bookable {

    private Set<Review> reviews;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "bookable", orphanRemoval = true)
    public Set<Review> getReviews() {
        return reviews;
    }
}

Bookable表示可以预订的几个实体的超类,并且还具有其他一些字段,为简洁起见,这些字段被省略。我的问题是:mappedBy可以用来做什么,因为数据库中没有bookable表?有不同的子类型,那么如何将子类设置为引用方?

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Setter
public class Review extends HasId {

    private Long id;
    private Bookable bookable;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    public Long getId() {
        return this.id;
    }

    @JoinColumn(name = "bookable_id", nullable = false, updatable = false)
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    public Bookable getBookable() {
        return bookable;
    }

    @Override
    public boolean equals(Object o) {
        // Left out for brevity
    }

    @Override
    public int hashCode() {
        // Left out for brevity
    }
}

Review类中,为了简洁也省略了几个字段。

使用上面的代码,我遇到了

org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: Review.main_bookable in SportsFacility.reviews

*当Bookable是实体时,某些外键列被复制到子类的表中,并且对于子类始终为null。例如。供应商(引用方)无法访问其体育设施(拥有方),因为vendor_id在sports_facility表中为null,而仅在bookable表中进行了正确设置。这就是为什么我不得不切换到MappedSuperclass的原因。

0 个答案:

没有答案