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

fie*_*die 5 java hibernate

我对Hibernate有一个奇怪的(对我而言)问题,我无法理解.下面的代码是我试图使用一个额外的实体CaseToSuggestion和Case作为我的聚合根,在实体Case和Suggestion之间使用属性建模ManyToOne关系:

@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;

   ...
}
Run Code Online (Sandbox Code Playgroud)

如果我为上述实体创建新对象,设置适当的关联,然后将它们与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);
Run Code Online (Sandbox Code Playgroud)

其次是 entityManager.persist(c);

如果我想向已经在数据库中的Case添加新关联,我将从EntityManager中检索要关联的Case和Suggestion实体,并将它们添加到新的CaseToSuggestion中:

CaseToSuggestion c2s = new CaseToSuggestion(c, s, fb);
c.getAssociatedSuggestions().add(c2s);
s.getAssociatedCases().add(c2s);
Run Code Online (Sandbox Code Playgroud)

其次是 entityManager.merge(c);

CaseToSuggestion实体存储在数据库中,但对于每个条目,我得到一个带有新生成id的"ghost entry",所有字段为null:

+----+----------+--------+--------------+
| 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 |
+----+----------+--------+--------------+
Run Code Online (Sandbox Code Playgroud)

有没有人知道可能导致这种情况的原因?

fie*_*die 1

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