休眠一到零或一个映射 [英] Hibernate one to zero or one mapping

查看:95
本文介绍了休眠一到零或一个映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class A {
private B b;
// ...获得者和设置者
}

class B {
private A a;

类映射指定:

 <多对一名称=bclass =B
insert =falseupdate =false
column = idunique =true/>

和B类映射指定:

 < one-to-one name =aclass =Aconstrained =true/> 

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

  if(b == null)

然而,似乎b永远不会为null。



我能做什么解答方案

答案是在A中多对一的语句中添加not-found =ignore :

 <多对一名称=bclass =Bnot-found =忽略插入=falseupdate =falsecolumn =idunique =true/> 

我试着简单地向B推荐lazy =false,但这导致了。HibernateObjectRetrievalFailureException每次我加载的有无b的A



请参阅此线程以获取更多信息:



<一个href =https://forum.hibernate.org/viewtopic.php?p=2269784&sid=5e1cba6e2698ba4a548288bd2fd3ca4e =noreferrer> https://forum.hibernate.org/viewtopic.php?p=2269784&sid = 5e1cba6e2698ba4a548288bd2fd3ca4e


I'm trying to map a one to "zero or one" relationship in 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:

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

and Class B's mapping specifies:

<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. So I can do this (in class A):

if (b == null)

However, it seems that b is never null.

What can I do about this?

解决方案

The answer was to add not-found="ignore" to the many-to-one statement in A:

<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.

See this thread for more information:

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

这篇关于休眠一到零或一个映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆