我面临与this question相同的情况,没有有用的答案。
当我向一对多关系的许多部分添加一个新元素时,Hibernate会生成两个查询,一个用于插入,另一个用于将外键更新为父级。
为什么需要第二个查询?插入中是否设置了父级的id? 有没有办法避免这种情况?
Hibernate:
/* insert mydomain.LanguageKnowledge */
insert
into
languageKnowledge
(language_fk, level_fk, personId_fk)
values
(?, ?, ?)
Hibernate:
/* create one-to-many row mydomain.Person.offeredLanguages */
update
languageKnowledge
set
personId_fk=?
where
id=?
public class LanguageKnowledge {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
@Enumerated(STRING)
@Column(name = "language_fk")
private LanguageIso639_3 language;
@Enumerated(STRING)
@Column(name = "level_fk")
private LanguageLevel level;
protected LanguageKnowledge() {
}
}
public class Person {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
@OneToMany(fetch = EAGER, cascade = {ALL}, orphanRemoval = true)
@JoinColumn(name = "personId_fk", referencedColumnName = "id", nullable = false)
private final Set<LanguageKnowledge> offeredLanguages = new HashSet<>();
public Person(Set<LanguageKnowledge> offeredLanguages) {
addOfferedLanguages(offeredLanguages);
}
protected Person() {
}
public void addOfferedLanguages(Set<LanguageKnowledge> offeredLanguages) {
this.offeredLanguages.addAll(offeredLanguages);
}
public void removeOfferedLanguages(Set<LanguageKnowledge> offeredLanguagesToRemove) {
this.offeredLanguages.removeAll(offeredLanguagesToRemove);
}
}
答案 0 :(得分:1)
该关联是单向的,因此Person
是拥有方(因为它是唯一的一方)。
使关联成为双向关联,并使LanguageKnowledge
成为关联所有者。这样您就可以避免冗余更新,因为外键值将被指定为LanguageKnowledge
的插入语句的一部分。