我有以下BaseNews
和News
实体:
@MappedSuperclass
public class BaseNews extends Model {
public static Model.Finder<Long, News> find = new Model.Finder<Long, News>(News.class);
public static News getNewsById(Long newsId) {
return find.byId(newsId);
}
public static List<News> getNewsList(int pageIndex, int pageSize) {
return find.where()
.findPagedList(pageIndex, pageSize)
.getList();
}
}
@Entity
@Table(name = "news")
public class News extends BaseNews implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// @ManyToOne
// private News baseNews;
@OneToMany(cascade = CascadeType.ALL)//,mappedBy = "baseNews")
@JoinTable(name = "news_similar",
joinColumns = {@JoinColumn(name = "base_news_id")},
inverseJoinColumns = {@JoinColumn(name = "similar_news_id")}
)
private List<News> similarNews;
//getters, setters...
}
在单向和双向情况下
select t0.id c0, t0.base_news_id c1 from news t0
给出错误未知列
base_news_id
我做错了吗?
我应该创建新的Entity NewsSimilar而不是使用joinable吗?
实际上,我正在反转现有表。
create table news_similar
(
id int auto_increment primary key,
base_news_id int not null,
similar_news_id int not null,
constraint news_similar_ibfk_1 foreign key (base_news_id) references news (id) on update cascade on delete cascade,
constraint news_similar_ibfk_2 foreign key (similar_news_id) references news (id) on update cascade on delete cascade
)
编辑:news_id是与其他领域完全无关的问题,无论如何解决了它。
最佳答案
原来我有ManyToMany关系,所以解决方案是这样的
@Entity
@Table(name = "news")
public class News extends BaseNews implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "news_similar",
joinColumns = {@JoinColumn(name = "base_news_id")},
inverseJoinColumns = {@JoinColumn(name = "similar_news_id")}
)
private List<News> similarNews;
//getters, setters...
}
阅读本文时出现此解决方案:
https://www.thoughts-on-java.org/ultimate-guide-association-mappings-jpa-hibernate/