在hibernate中,我通过共享主键使用一对一关系,每当我调用save方法插入父实体而不插入子实体时,就会出现以下异常。
org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.example.sms.domain.Child.parent]

下面给出了具有父类实体映射的子类实体代码
@Entity
@Table(name = "t_child")
public class Child {
@Id
@Column(name="user_id", unique=true, nullable=false)
@GeneratedValue(generator="gen")
@GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="user"))
private Long id;
@OneToOne(optional = false,fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private Parent parent;在父类实体中,我映射了如下所示的子类实体
@OneToOne(mappedBy="parent", cascade=CascadeType.ALL)
private Child child;是否有任何方法只保存父实体而不插入子实体?
发布于 2017-11-15 22:40:09
最后,过了一天,我自己找到了解决办法。 这个代码是正确的。Mapstruct在将Dto转换为域对象时出现了问题。
@Mappings({
@Mapping(source = "fatherName", target = "child.childDetail.fatherName"),
@Mapping(source = "motherName", target = "child.childDetail.motherName"),
@Mapping(source = "firstName", target = "child.childDetail.firstName"),
@Mapping(source = "lastName", target = "child.childDetail.lastName"),
@Mapping(source = "dateOfBirth", target = "child.childDetail.dateOfBirth"),
})
public User ParentDtoToParent(ParentDto parentDto);我使用的DTO对象与存储每个子细节时使用的对象相同,但为了存储父实体,我没有发送任何Json格式的子细节值。因此,在Hibernate保存对象时,mapstruct自动将空值分配给Child属性(名字、姓氏等),对象的属性为空值,而不是空对象。
https://stackoverflow.com/questions/47294277
复制相似问题