我正试图在Hibernate中将一个映射到"零或一"关系.我想我可能找到了一种使用多对一的方法.
class A {
private B b;
// ... getters and setters
}
class B {
private A a;
}
Run Code Online (Sandbox Code Playgroud)
A类的映射指定:
<many-to-one name="b" class="B"
insert="false" update="false"
column="id" unique="true"/>
Run Code Online (Sandbox Code Playgroud)
和B类的映射指定:
<one-to-one name="a" class="A" constrained="true"/>
Run Code Online (Sandbox Code Playgroud)
我想要的是,当在数据库中找不到B的匹配行时,b为null.所以我可以这样做(在A级):
if (b == null)
Run Code Online (Sandbox Code Playgroud)
但是,似乎b永远不会为空.
我该怎么办?
小智 18
就像Boden所说,答案是not-found="ignore"
在A中添加多对一语句.使用注释执行此操作:
在A类:
@ManyToOne
@Cascade({ CascadeType.ALL })
@JoinColumn(name = "Id")
@NotFound(action=NotFoundAction.IGNORE)
private B b
Run Code Online (Sandbox Code Playgroud)
在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;
Run Code Online (Sandbox Code Playgroud)
答案是在A中的多对一语句中添加not-found ="ignore":
<many-to-one name="b" class="B" not-found="ignore" insert="false" update="false" column="id" unique="true"/>
Run Code Online (Sandbox Code Playgroud)
我试着像Rob H推荐的那样简单地将lazy ="false"添加到B,但每次加载没有B的A时都会导致HibernateObjectRetrievalFailureException.
请参阅本主题以获取更多信息:
https://forum.hibernate.org/viewtopic.php?p=2269784&sid=5e1cba6e2698ba4a548288bd2fd3ca4e