gpt4 book ai didi

jpa - 如何在 jpa 中定义可能的不存在关系?

转载 作者:行者123 更新时间:2023-12-05 03:14:11 27 4
gpt4 key购买 nike

假设我有一个表 Item,其中包含一个名为 user_id 的列和一个表 User 以及另一个名为 Superuser 的列:

CREATE TABLE Item(id int, user_id int, ..);  
CREATE TABLE User(id int, ..);
CREATE TABLE Superuser(id int, ..);

现在,所有项目都有一个用户条目,但只有一些项目有一个 super 用户条目,即 Item.user_id == User.id 总是和 Item.user_id == Superuser.id 是可选的。

我可以匹配用户部分,但我不知道如何映射 super 用户部分。例如,这不起作用:

@Entity
public class Item {
@ManyToOne(optional = true)
@JoinColumn(name = "user_id")
private Superuser su;
...

这只允许user_id为NULL,但我一直有一个user_id。
我需要的是告诉 jpa “即使会有一个外键”, super 用户表上也可能没有匹配的条目。

最佳答案

我设法解决了最具体的问题,因为我使用 hibernate 作为 JPA 后端。
Hibernate 有一个 NotFound正是针对这种情况的注释:

By default, when Hibernate cannot resolve the association because the expected associated element is not in database (wrong id on the association column), an exception is raised by Hibernate. This might be inconvenient for lecacy and badly maintained schemas. You can ask Hibernate to ignore such elements instead of raising an exception using the @NotFound annotation. This annotation can be used on a @OneToOne (with FK), @ManyToOne, @OneToMany or @ManyToMany association.

所以 Hibernate 解决方案看起来像这样:

@Entity
public class Item {
@ManyToOne(optional = true)
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "user_id")
private Superuser su;
...

我仍然想知道是否有 JPA 规范接受的其他方式。

关于jpa - 如何在 jpa 中定义可能的不存在关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26337664/

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