我在两个表之间有一对一的映射:
人->id |名称
person_status->id | person_id |状态
我按照hibernate用户指南创建一个一对一的单向映射。如果我们想要懒惰的联想,他们会说:
。。。使用带有@MapsId注释的单向@OneToOne关联要有效得多。
但他们没有提供这样的例子。我尝试了以下操作,但在保存记录时出现以下异常:
org.hibernate.id.IdentifierGenerationException:为类PersonStatusEntity生成空id
@Entity(name = "Person")
class PersonEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null,
val name: String,
@OneToOne(
//mappedBy = "person", //removed because I don't want bidirectional
cascade = [CascadeType.ALL],
fetch = FetchType.LAZY,
optional = false,
orphanRemoval = true
)
var personStatus: PersonStatusEntity
)
@Entity(name = "PersonStatus")
class PersonStatusEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null,
@OneToOne(fetch = FetchType.LAZY)
@MapsId
var person: PersonEntity? = null,
@Enumerated(EnumType.STRING)
val status: Status
)
我还尝试删除@GeneratedValue()
,但没有任何运气。
如代码中所写:
removed because I don't want bidirectional
如果你真的需要单向关联,请完全删除阻止
@OneToOne(
//mappedBy = "person", //removed because I don't want bidirectional
cascade = [CascadeType.ALL],
fetch = FetchType.LAZY,
optional = false,
orphanRemoval = true
)
var personStatus: PersonStatusEntity
并仅将OneToMany保留为PersonStatus。
此外,应该在PersonStatus中删除GeneratedValue,因为您试图使用MapsId注释使用共享PK。
注意:如果您认为需要单向关联,那么应该在PersonEntity端添加mappingBy。还要注意的是,只有一侧的单向侧才会真正懒惰。