1
我們假設我有兩個實體:Body
和Leg
。 Leg
有字段side
(它的值可以是Left
或Right
),也有Body
的外鍵。在@Where中使用@OneToOne
我敢肯定,Body
的每個實例只有一個左腿,只有一個右腿。所以我想基於side
字段的值在Body
和Leg
之間創建2 One-To-One
映射。
換句話說,我在數據庫級別有One-To-Many
關係,並且想要在模型中獲得One-To-One
。可能嗎?
Body.scala
@Entity
@Table(name = "body")
case class Body(
@([email protected])
var id: String = null,
@([email protected])(cascade = Array(CascadeType.ALL), mappedBy = "body")
var leftLeg: Leg = null,
@([email protected])(cascade = Array(CascadeType.ALL), mappedBy = "body")
var rightLeg: Leg = null
)
Leg.scala
@Entity
@Table(name = "leg")
case class Leg(
@([email protected])
var id: String = null,
@([email protected])
@([email protected])(name = "body_id")
var body: Body = null,
@([email protected])
var side: String = null
)
當然,我可以做到這一點作爲One-To-Many
並添加2個干將每條腿,但我也需要通過左腿過濾(for例如)在reporsitory,所以想寫這樣的事情
@Query(value = "select b from Body b where b.id = ?1 and b.leftLeg.size = ?2)
def findBodyByLegSize(bodyId: String, size: String): Body