【发布时间】:2016-09-16 14:50:37
【问题描述】:
我的应用程序中有两个由列表表示的多对一关系。对于“ChapterSection - ManyToOne - Chapter”关系,在持久化实体时将外键插入表中(在表“ChapterSection”中存储“Chapter”的外键)。对于其他关系,即“Chapter” - 多对一 - 文档”。
我使用 ddl.generation “drop-and-create-tables”。在数据库中,我可以看到,“Chapter.fk_document_iddocument”列被标记为引用文档 ID 的索引外键。 (我使用 EclipseLink 和 MySQL)。
我看不出这两种关系之间的区别,以及为什么一种有效而另一种无效。
文档实体:
@Entity
public class Document implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="iddocument")
private Long id;
@Column(name="document_name")
private String documentName;
@OneToMany(mappedBy="Document", cascade = CascadeType.PERSIST)
private List<Chapter> chapters;
@Enumerated(EnumType.STRING)
@Column(name="document_type")
private DocumentTypes documentType;
//...getters, setters and other generated methods
章节实体:
@Entity
public class Chapter implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="idchapter")
private Long id;
@Column(name="chapter_order")
private int chapterOrder;
@Column(name="parent_chapter")
private Long parentChapter;
@Column(name="chapter_name")
private String chapterName;
@ManyToOne(optional=false)
@JoinColumn(name="fk_document_iddocument")
private Document document;
@OneToMany(mappedBy="Chapter", cascade=CascadeType.PERSIST)
List<ChapterSection> chapterSections;
//...getters, setters and other generated methods
章节实体:
@Entity
public class ChapterSection implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="idchaptersection")
private Long idChapterSection;
@Column(name="section_name")
private String sectionName;
@Column(name="section_order")
private int sectionOrder;
@Column(name="content")
private String content;
@ManyToOne
@JoinColumn(name="fk_chapter_idchapter")
private Chapter chapter;
//...getters, setters and other generated methods
我创建文档的方法:
public void createDocument() {
List <Chapter> chapters = new ArrayList<>();
for (int i = 0; i <= 4; i++) {
Chapter chapter = new Chapter();
chapter.setChapterOrder(i);
chapter.setChapterName("Chapter "+i);
List <ChapterSection> chapterSections = new ArrayList<>();
for (int j = 0; j <= 4; j++) {
ChapterSection chapterSection = new ChapterSection();
chapterSection.setChapter(chapter);
chapterSection.setSectionName("Chapter "+i+" Section");
chapterSection.setSectionOrder(j);
chapterSection.setContent("Kapitel "+i+ ", Section "+j+" Content!");
chapterSections.add(chapterSection);
}
chapter.setChapterSections(chapterSections);
chapters.add(chapter);
}
document.setDocumentName("My Doc");
document.setChapters(chapters);
document.setDocumentType("My Doc Type");
documentDAO.persistDocument(document);
}
【问题讨论】:
-
如果您可以改进您的问题,可能很容易解决。究竟是什么问题?
标签: jpa eclipselink