休眠一到零或一个映射

2022-09-03 12:30:11

我试图在Hibernate中映射一到“零或一”的关系。我想我可能已经找到了一种使用多对一的方法。

class A {
  private B b;
  // ... getters and setters
}

class B {
  private A a;
}

类 A 的映射指定:

<many-to-one name="b" class="B" 
insert="false" update="false" 
column="id" unique="true"/>

和 B 类的映射指定:

<one-to-one name="a" class="A" constrained="true"/>

我希望的是,当在数据库中找不到 B 的匹配行时,b 为 null。所以我可以这样做(在A类中):

if (b == null)

但是,似乎 b 从不为空。

我该怎么办?


答案 1

正如博登所说,答案是添加到A中的多对一语句中。通过注释来做到这一点:not-found="ignore"

在 A 类中:

@ManyToOne
@Cascade({ CascadeType.ALL })
@JoinColumn(name = "Id")
@NotFound(action=NotFoundAction.IGNORE)
private B b

在B类中:

@Id
@GeneratedValue(generator = "myForeignGenerator")
@org.hibernate.annotations.GenericGenerator(
    name = "myForeignGenerator",
    strategy = "foreign",
    parameters = @Parameter(name = "property", value = "a")
)
private Long subscriberId;

@OneToOne(mappedBy="b")
@PrimaryKeyJoinColumn
@NotFound(action=NotFoundAction.IGNORE)
private A a;

答案 2

答案是将 not-found=“ignore” 添加到 A 中的多对一语句中:

<many-to-one name="b" class="B" not-found="ignore" insert="false" update="false" column="id" unique="true"/>

我尝试简单地按照 Rob H 的建议将 lazy=“false” 添加到 B 中,但每次我加载一个没有 B 的 A 时,这都会导致 HibernateObjectRetrievalFailureException。

有关详细信息,请参阅此主题:

https://forum.hibernate.org/viewtopic.php?p=2269784&sid=5e1cba6e2698ba4a548288bd2fd3ca4e


推荐