gpt4 book ai didi

java - Hibernate 为新的子实体生成 ghost 条目

转载 作者:搜寻专家 更新时间:2023-11-01 00:51:34 24 4
gpt4 key购买 nike

我对 Hibernate 有一个奇怪的(无论如何对我来说)问题,我无法理解。下面的代码是我尝试使用一个附加实体 CaseToSuggestion 与实体 Case 和 Suggestion 之间的属性对 ManyToOne 关系进行建模,其中 Case 是我的聚合根:

@Entity
@Table(name = "sga_cases")
public class Case {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

// Business key
@Column(name = "caseid", unique = true, nullable = false)
private String caseId;

...

@OneToMany(mappedBy = "associatedCase", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<CaseToSuggestion> associatedSuggestions = new HashSet<CaseToSuggestion>();

...
}


@Entity
@Table(name = "sga_suggestions")
public class Suggestion {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(name = "suggestionid", unique = true, nullable = false)
private String suggestionId;

@Column(name = "localizationkey", nullable = false)
private String localizationKey;

@OneToMany(mappedBy = "associatedSuggestion", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<CaseToSuggestion> caseMapping = new HashSet<CaseToSuggestion>();

...
}


@Entity
@Table(name = "sga_case2suggestion")
public class CaseToSuggestion {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(name = "feedback")
private float feedback;

@ManyToOne
@JoinColumn(name = "caseid")
private Case associatedCase;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "suggestionid")
private Suggestion associatedSuggestion;

...
}

如果我为上述实体创建新对象,设置适当的关联,然后将它们存储在 EntityManager 中,一切正常:

Case c = new Case(...)
Suggestion sugg = new Suggestion(...);
CaseToSuggestion case2sugg = new CaseToSuggestion(c, sugg, 1.0f);

c.getAssociatedSuggestions().add(case2sugg);
sugg.getAssociatedCases().add(case2sugg);

紧随其后的是 entityManager.persist(c);

如果我想向数据库中已有的案例添加新关联,我会从 EntityManager 中检索我想关联的案例和建议实体,并将它们添加到新的 CaseToSuggestion:

CaseToSuggestion c2s = new CaseToSuggestion(c, s, fb);
c.getAssociatedSuggestions().add(c2s);
s.getAssociatedCases().add(c2s);

紧随其后的是 entityManager.merge(c);

CaseToSuggestion 实体存储在数据库中,但对于每个条目,我都会得到一个“幽灵条目”,其中包含新生成的 ID,所有字段均为空:

+----+----------+--------+--------------+
| id | feedback | caseid | suggestionid |
+----+----------+--------+--------------+
| 3 | 1 | 3 | 1 |
| 4 | 1 | 4 | 2 |
| 5 | 1 | 5 | 2 |
| 6 | 0 | NULL | NULL |
| 7 | 1 | 6 | 2 |
| 8 | 0 | NULL | NULL |
| 9 | 1 | 7 | 2 |
| 10 | 0 | NULL | NULL |
+----+----------+--------+--------------+

有人知道是什么原因造成的吗?

最佳答案

好的,我知道了。删除建议中的 OneToMany-Mapping 完全解决了我的问题。

关于java - Hibernate 为新的子实体生成 ghost 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13361322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com