英文:
Did I define many to one correctly in the composite key?
问题
我已将实体定义如下:
@Entity
data class Environment(
@EmbeddedId
var key: EnvStageId? = null,
var value: String = ""
)
@Embeddable
class EnvStageId(
@ManyToOne
var stage: Stage? = null,
var key: String = ""
) : Serializable
@Entity
data class Stage(
@field:Id
var env: String = "",
var description: String = ""
)
我使用了 Hibernate 并且它按预期生成了表格。问题是,我是否正确地定义了 ManyToOne
,或者是否有遗漏的部分?根据这个教程,我需要在一侧定义 ManyToOne
,在另一侧定义 OneToMany
。
英文:
I have defined entities as the following:
@Entity
data class Environment(
@EmbeddedId
var key: EnvStageId? = null,
var value: String = ""
)
@Embeddable
class EnvStageId(
@ManyToOne
var stage: Stage? = null,
var key: String = ""
) : Serializable
@Entity
data class Stage(
@field:Id
var env: String = "",
var description: String = ""
)
I used Hibernate and it generates the tables as expected. The question is, did I define ManyToOne
correctly or did I miss something? Regarding this this tutorial, I have to define ManyToOne
on one side and OneToMany
on other side.
答案1
得分: 2
你不必定义关系的另一侧。只有在你想要从两侧都访问关系时,才需要这样做。
如果你想要这样做,你需要像这样做。我对@Embeddable
不太熟悉,但我想它应该类似于这样:
@Entity
data class Environment(
@OneToMany(mappedBy = "environment", cascade = CascadeType.ALL)
var stages: List<Stage>
)
@Entity
data class Stage(
@ManyToOne
var environment: Environment
)
英文:
You don't have to define the other side of the relationship. You only have to do it if you want to have access to the relations from both side.
If you want to do that you'll have to do something like this. I'm not familiar with @Embeddable
, but I imagine that it should be similar to this:
@Entity
data class Environment(
@OneToMany(mappedBy = "environment", cascade = CascadeType.ALL)
var stages: List<Stage>
)
@Entity
data class Stage(
@ManyToOne
var environment: Environment
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论