【发布时间】:2016-10-14 00:28:54
【问题描述】:
每个人。我是 Hibernate 的新手,并且在对象持久化方面遇到了一些意想不到的麻烦。 以下是我的实体类的相关摘录:
TAAnalysis.java
public class TAnalysis implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer unAnalysis;
@JoinColumn(name = "uninttest", referencedColumnName = "un_inttest", nullable = false)
@ManyToOne(fetch = FetchType.EAGER, optional = false, cascade = CascadeType.ALL)
private TIntTest tIntTest;
@OneToOne(optional = false, mappedBy = "tAnalysis", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private TBaseComp tBaseComp;
@OneToOne(optional = false, mappedBy = "tAnalysis", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private TWellTest tWellTest;
@OneToOne(optional = false, mappedBy = "tAnalysis", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private TGasPart tGasPart;
@OneToOne(optional = false, mappedBy = "tAnalysis", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private TAddOnComp tAddOnComp;
}
TIntTest.java
public class TIntTest implements Serializable, ISimpleEntity {
@Id
@GeneratedValue (strategy = GenerationType.SEQUENCE)
@Column (name = "un_inttest", nullable = false)
private Integer unInttest;
@OneToMany (cascade = CascadeType.ALL, mappedBy = "tIntTest")
private Set<TAnalysis> tAnalysisSet;
}
TBaseComp.java
public class TBaseComp implements Serializable {
@Id
@Column(name = "un_analysis", nullable = false)
private Integer unAnalysis;
@MapsId
@JoinColumn(name = "un_analysis", referencedColumnName = "un_analysis", nullable = false, insertable = false, updatable = false)
@OneToOne(optional = false, fetch = FetchType.EAGER)
private TAnalysis tAnalysis;
}
与 TAnalysis 有 [@OneToOne] 关系的其他类(TAddOnComp、TGasPart 和 TWellTest)(种“子类”)与 TBaseComp 共享相同的结构。
所有列出的关系都必须不为空。因此,当我坚持新的 TAnalysis 实例时,我必须为其指定 TIntTest 对象,并且还必须创建“子类”实例。我就是这样做的:
EntityManager em = emf.createEntityManager();
TAnalysis an = new TAnalysis();
TBaseComp baseComp = new TBaseComp();
TGasPart gasPart = new TGasPart();
TAddOnComp addInComp = new TAddOnComp();
TWellTest wellTest = new TWellTest();
an.setTBaseComp(baseComp);
an.setTGasPart(gasPart);
an.setTAddOnComp(addInComp);
an.setTWellTest(wellTest);
baseComp.setTAnalysis(an);
gasPart.setTAnalysis(an);
addInComp.setTAnalysis(an);
wellTest.setTAnalysis(an);
TIntTest intTest = em.find(TIntTest.class, 10);
an.setTIntTest(intTest);
an = em.merge(an);
//baseComp = em.merge(baseComp);
//gasPart = em.merge(gasPart);
//addOnComp = em.merge(addOnComp);
//wellTest = em.merge(wellTest);
//em.persist(an);
em.getTransaction().commit();
合并操作抛出异常
org.hibernate.PropertyValueException: not-null property references a null or transient value : org.foladesoft.omnibus_client_maven.entities.TAnalysis.tIntTest"
我不明白为什么会发生这种情况,因为我指定了请求的属性值an.setTIntTest(intTest);
为了解决我的问题,我使用 em.persist(an) 而不是合并,但在 commit 阶段遇到了另一个异常:PostgreSQL 的 外键违规异常 告诉我我正在尝试在将新记录插入 TAnalysis 之前将记录插入 TAddOnComp。
能否请您告诉我为什么会遇到这些问题以及如何使我的应用程序正常工作。
【问题讨论】:
-
我建议调试 em.find 是否返回非空 TIntTest。此外,让 Hibernate 记录更新查询,包括参数。