我正确地在复合键中定义了一对多吗?

huangapple go评论74阅读模式
英文:

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 = &quot;environment&quot;, cascade = CascadeType.ALL)
    var stages: List&lt;Stage&gt;
)

@Entity
data class Stage(
    @ManyToOne
    var environment: Environment
)

huangapple
  • 本文由 发表于 2020年10月14日 04:40:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64342851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定