【发布时间】:2017-01-24 14:40:18
【问题描述】:
是否可以在 Section.class 中进行级联保存? 我创建 Section 对象并添加没有 id 的新问题。 当我尝试保存时出现错误:
org.postgresql.util.PSQLException: 错误: 在表上插入或更新 “question_to_section”违反外键约束 "fk_2br9f09ok965403a9rv5y2n10" 详细信息:键 (question_id)=(0) 不是 出现在表“问题”中。
我也尝试过使用@Embedded 注解,但没有成功。
节类:
@Table(name = "section")
@Entity(name = "section")
public class Section implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
@JsonProperty
long id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "section")
Set<QuestionToSection> questions = new HashSet<QuestionToSection>(0);
...
}
问题到部分类
@Entity(name = "question_to_section")
@Table(name = "question_to_section")
@IdClass(QuestionSectionId.class)
public class QuestionToSection implements Serializable {
@Id
long sectionId;
@Id
long questionId;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "sectionId", nullable = false, updatable = false, insertable = false, referencedColumnName = "id")
Section section;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL )
@JoinColumn(name = "questionId", nullable = false, updatable = false, insertable = false, referencedColumnName = "id")
Question question;
...
}
QuestionSectionId
public class QuestionSectionId implements Serializable {
long questionId;
long sectionId;
}
【问题讨论】:
-
这里的真实关系似乎是
Questions 和Sections 之间的多对多关系。插入QuestionToSection实体有什么意义? -
您的问题与 updatable=false, insertable=false 的关系有关,为了让您的 M-M 您不允许级联插入
标签: java hibernate jpa annotations java-persistence-api