有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我最近读到了弗拉德·米哈尔恰(Vlad Mihalcea)的一篇article关于映射与JPA和Hibernate关系的最佳方式的文章。我也想为我的类使用所描述的映射,但我的引用端必须是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表示可以预订的几个实体的超类,并且还有一些为简洁起见而省略的其他字段。我这里的问题是:由于数据库中没有bookable表,我可以为mappedBy使用什么?有不同的子类型,那么如何将子类设置为引用端呢

@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是一个实体时,某些外键列被复制到子类的表中,并且对于子类总是空的。例如,供应商(参考方)无法访问其体育设施(拥有方),因为供应商id在sports_facility表中为空,而只有在bookable表中正确设置。这就是为什么我必须切换到MappedSuperclass


共 (0) 个答案