gpt4 book ai didi

java - 使用 ID 的单向 @OneToOne

转载 作者:行者123 更新时间:2023-12-01 18:15:01 26 4
gpt4 key购买 nike

我想创建一个@OneToOne使用 ID 的单向关系。让我们考虑以下示例:

@Table(name = "user")
@Entity
class User (

@Id
@GeneratedValue(...)
var id: Long? = null,

@OneToOne
var address: UserAddress? = null
)

@Table(name = "user_address")
@Entity
class UserAddress(
@Id
var id: Long? = null,

(...)
)

在数据库上,user_address.id 有一个外键约束引用user.id 。我尝试使用许多不同的注释组合,但仍然遇到删除问题。我正在使用用户的 JpaRepository ,当 userRepository.deleteById(id) 时被调用时,仅删除子项 ( address ),但不删除父项 ( user )。我真的很想保留@Id名称为“id”的列。这可能吗?

编辑

当我使用以下代码时:

@Table(name = "user")
@Entity
class User (

@Id
@GeneratedValue(...)
var id: Long? = null,

@OneToOne(cascade = [CascadeType.All])
@JoinColumn(name = "id", referencedColumnName = "id")
var address: UserAddress? = null
)

@Table(name = "user_address")
@Entity
class UserAddress(
@Id
var id: Long? = null,


@OneToOne(mappedBy = "address")
var user: User? = null
(...)
)

何时 userRepository.deleteById(id)被调用,唯一的 child 被删除。我不知道为什么......此外我想保持这种关系单向。

编辑用户存储库

@Repository
interface UserRepository : JpaRepository<User, Long> {
}

编辑 - 已解决好的。我有另一个实体(我们称之为公司),其中有 Set<User> 。事实证明,拥有它 Fetch。 EAGER 防止用户被删除...感谢大家抽出时间。我不知道这可能是一个问题,因此我没有提到它......

最佳答案

您需要的是级联删除,可以通过将 orphanRemoval=true 传递给 @OneToOne 注释来实现。

示例:

    @OneToOne(orphanRemoval=true)
var address: UserAddress? = null

或者,您也可以使用 cascade=CascadeType.REMOVE 而不是 orphanremoval=true

借自ObjectDB :

If orphanRemoval=true is specified the disconnected Address instance is automatically removed. This is useful for cleaning up dependent objects (e.g. Address) that should not exist without a reference from an owner object (e.g. Employee). If only cascade=CascadeType.REMOVE is specified no automatic action is taken since disconnecting a relationship is not a remove operation.

希望这有帮助!

关于java - 使用 ID 的单向 @OneToOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60389169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com