java - org.hibernate.PropertyValueException

标签 java hibernate exception

我有这些 Pojo:

public class ParticipantPojo implements Serializable
.....
@OneToMany(mappedBy = "participant", cascade = CascadeType.ALL)
private Set<ParticipantIdentificationNumberPojo> identificationNumbers;

public class ParticipantIdentificationNumberPojo implements Serializable
 ......
@ManyToOne
@JoinColumn(name = "PARTICIPANT", nullable = false)
private ParticipantPojo participant;

当我想创建一个新参与者时

 ParticipantPojo pojo= new ParticipantPojo ();
 ...
 Set<ParticipantIdentificationNumberPojo> identSet = new HashSet<ParticipantIdentificationNumberPojo>();
 ParticipantIdentificationNumberPojo identInfo= new ParticipantIdentificationNumberPojo();
 identInfo.setType("xyz");
 identInfo.setNumber(12345);
 identSet.add(identInfo);
 pojo.setIdentificationNumbers(identSet);

并保存

 session.save(pojo);

我收到以下错误:

org.hibernate.PropertyValueException: not-null property references a null or transient value: de.seeburger.marktpartnerdaten.database.pojo.ParticipantIdentificationNumberPojo.participant

在博客中我找到了设置 nullable=true 的解决方案

@JoinColumn(name = "PARTICIPANT", nullable = false)

但这不是我想要的(参与者不应该为空!)...设置 nullable=true 创建另一个异常

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: de.seeburger.marktpartnerdaten.database.pojo.ParticipantPojo

我认为问题是,Hibernate 不会保存参与者并使用 ID 来保存参与者IdentificationNumber...但我没有找到针对我的异常的解决方案:-(

最佳答案

您已创建与作为定义方的 ParticipantPojo 的双向关系(使用 @OneToMany 注释中的 mappedBy 属性) 。 ParticipantIdentificationNumberPojo 是关系的拥有方,您必须在拥有方注册定义方的实例。

因此,您必须按如下方式注册 ParticipantPojo 实例:

ParticipantPojo pojo= new ParticipantPojo ();
...
Set<ParticipantIdentificationNumberPojo> identSet = new HashSet<ParticipantIdentificationNumberPojo>();
ParticipantIdentificationNumberPojo identInfo= new ParticipantIdentificationNumberPojo();
identInfo.setType("xyz");
identInfo.setNumber(12345);
identInfo.setParticipantPojo(pojo); // <-- Registering the instance on the owning side.
identSet.add(identInfo);
pojo.setIdentificationNumbers(identSet);

理想情况下,即使您已声明双向关系,您也必须在两个方向上注册该关系。然而,如果您在拥有方设置值,Hibernate 将使事情变得容易,因为那一方包含外键;一旦您考虑到这一点,您就会意识到收到第二条错误消息的原因 - 外键不能为空。

关于java - org.hibernate.PropertyValueException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6691348/

相关文章:

java - 如何重写java循环并将临时结果保存到java8流

java - Spring JPA- hibernate : Batch insert execute too much select nextval (‘sequence’ )

java - 由 : java. lang.ClassNotFoundException : org. apache.commons.io.FileUtils、maven pom.xml 引起

java - 并发,随机化/改组队列?

java - 使用 JColorChooser 设置 JButton 的前景色和背景色

java - 围绕断言语句的迭代器会影响生产构建的性能吗?

c++ - 在什么情况下EXCEPTION_RECORD链接到另一个嵌套异常?

java - 如何使用 Hibernate 检索类的成员对象?

java - 如何在hibernate中不添加引用@Entity的情况下触发外键关系?

c++ - 当涉及多个异常处理时,何时调用析构函数?