【发布时间】:2020-11-14 05:58:00
【问题描述】:
我有三个具有关系的实体。
public class Site {
@OneToMany
private List<Page> pages;
}
public class Page {
@OneToMany
private List<Article> articles;
@OneToMany
private List<TopArticle> topArticles;
}
public class Article {
@ManyToOne
private Page page;
}
public class TopArticle {
@ManyToOne
@JoinColumn(name = "PageId")
private Page page;
@OneToOne
@JoinColumn(name = "ArticleId")
private Article article;
}
TopArticle 中的字段page 和arctile 具有数据库限制 - NOT NULL。 (需要限制)
我必须保存所有关联的站点。
Article article = new Article();
TopArticle topArticle = new TopArticle();
Page page = new Page();
page.getArticles().add(article);
page.getTopArticles().add(topArticle);
Site site = new Site();
site.getPages().add(page);
siteDAO.save(site);
有时它会保存网站。 但有时它会抛出错误。
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into column 'ArticleId', table '...TopArticle'; column does not allow nulls. INSERT fails
好像Page保存后,尝试保存关联List article和List topArticles强>。 也许,当 List article 在 List topArticles 之前保存时,它会起作用。 以另一种方式失败。
问题:
在 JPA 中保存属性顺序有问题吗?
如何强制 Hibernate 在 topArticles 之前保存 文章?
还有其他解决办法吗?
谢谢
【问题讨论】:
标签: java sql hibernate spring-data-jpa