简体   繁体   English

Hibernate一到零或一个映射

[英]Hibernate one to zero or one mapping

I'm trying to map a one to "zero or one" relationship in Hibernate. 我正试图在Hibernate中将一个映射到“零或一”关系。 I think I may have found a way using a many-to-one. 我想我可能找到了一种使用多对一的方法。

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

class B {
  private A a;
}

Class A's mapping specifies: A类的映射指定:

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

and Class B's mapping specifies: 和B类的映射指定:

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

What I would like is for b to be null when no matching row for B was found in the database. 我想要的是,当在数据库中找不到B的匹配行时,b为null。 So I can do this (in class A): 所以我可以这样做(在A级):

if (b == null)

However, it seems that b is never null. 但是,似乎b永远不会为空。

What can I do about this? 我该怎么办?

Like Boden said, the answer is to add not-found="ignore" to the many-to-one statement in A. Doing this with annotation: 像Boden说的那样,答案是在A中的多对一语句中添加not-found="ignore" 。使用注释执行此操作:

In Class A: 在A类:

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

in Class 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;

The answer was to add not-found="ignore" to the many-to-one statement in A: 答案是在A中的多对一语句中添加not-found =“ignore”:

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

I tried simply adding lazy="false" to B as Rob H recommended, but that resulted in a HibernateObjectRetrievalFailureException everytime I loaded an A that had no B. 我试着像Rob H推荐的那样简单地将lazy =“false”添加到B,但每次加载没有B的A时都会导致HibernateObjectRetrievalFailureException。

See this thread for more information: 请参阅本主题以获取更多信息:

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

Try setting lazy="false" on the many-to-one element. 尝试在多对一元素上设置lazy =“false”。 That should force Hibernate to try to fetch the association ("B") when the first object ("A") is loaded. 这应该强制Hibernate在加载第一个对象(“A”)时尝试获取关联(“B”)。 The property in "A" will either be initialized with a real instance of "B" or null. “A”中的属性将使用“B”的实例或null进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM