最近,我读了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的原因。