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

时间:2012-11-13 13:10:31

标签: java hibernate

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

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

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

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

后跟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 |
+----+----------+--------+--------------+

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

1 个答案:

答案 0 :(得分:1)

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