【发布时间】:2019-01-29 20:02:16
【问题描述】:
我有一个多对一的关系,我希望它可以为空。 这是父母:
@Entity
@Table(name = "C_CUSTOMER")
class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany (fetch = FetchType.LAZY, mappedBy="user", cascade = CascadeType.REMOVE)
private List<Profile> profiles;
}
还有孩子:
@Entity
@Table(name = "C_PROFILE")
class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(optional = true)
@JoinColumn(nullable = true, name = "user_id", referencedColumnName = "id", insertable = false, updatable = false)
private User user;
}
当我尝试保存没有 userId 的配置文件时,抛出以下错误:
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : fr.entity.Profile.user -> fr.entity.User
如果字段 userId 有值,那么它工作顺利。
我尝试了一堆关于 SO 的其他问题的答案,但到目前为止没有任何效果。最简单的方法是放弃实体文件中的关系并使用Integer customerId,但这对我来说并不令人满意,因为这意味着级联删除将不再起作用。
提前致谢。
编辑
问题来自实体 dto 映射。我添加了一个关于它的答案,如果我遇到解决方法可能会进行编辑。
【问题讨论】:
-
能否在问题中添加
Profilepojo? -
先保存
User,然后再添加到Profile实体。还请确保在填充User和Profile时,将每个实体添加到另一个实体中,从而创建双向关系。 -
只有当
User为null时才会出现错误,所以我不想添加它。我希望该字段为null。 -
你确定吗?因为Hibernate抱怨用户未保存!
-
好吧,我刚刚结束了它的新调试,然后... 结果用户字段 不是 为空。 Mea culpa - 它试图添加一个
User,所有字段都为空。太好了......现在的问题是:Userbe null 不应该吗?或者我错过了什么。
标签: java hibernate jpa mapstruct