编程语言
首页 > 编程语言> > java – Hibernate是否总是加载关联对象,即使它可以为null?

java – Hibernate是否总是加载关联对象,即使它可以为null?

作者:互联网

我有一个关于Hibernate的问题.

我有两个具有多对一关系的对象:

例如:
对象1:

 public class Person {

 @Basic
 @Column(length = 50)
 protected String name;

 @NotFound(action=NotFoundAction.IGNORE)
 @ManyToOne(fetch = FetchType.EAGER)
 @JoinColumn(name = "groupCode", referencedColumnName = "code", updatable=false)
 protected Group group;

 ...all the getters and setters...
 }

对象2:

 public class Group {
  @Id
  @Basic
  @Column(length = 3, nullable = false)
  protected String code;

  @Basic
  @Column(length = 30, nullable = false)
  protected String groupName;

   @Basic
   @Column(precision = 15, scale = 0)
   protected long exampleFieldId;

   ...rest of code....
  }

我试图让这个例子尽可能简单.我的问题是Person上的关联对象(Group)可以为null.目前,当我加载一个特定的Person并抛出异常时,Hibernate会加载一个Group实例,因为它无法将exampleFieldId设置为null(因为它是一个基本类型).

我可以通过将long更改为Long来停止此错误但是,我会认为Person上的Group对象应该为null,因此首先没有加载Group对象?

有没有人知道Hibernate是否加载了相关对象而不管它是否为空,或者我是否错过了一些重要的注释?

谢谢

解决方法:

正如Firo所说:

have you disabled lazy loading and set fetchmnode to join because
NHibernate has to fetch them to decide if it should nullify it or not
and it can not decide that only with an id

这似乎与您遇到的问题相同,即使它在NHibernate中也是如此.值得一试!

Why does Hibernate attempt to load “not-found=ignore” associations?

编辑:可能是你缺少@Fetch(FetchMode.JOIN).

标签:java,annotations,hibernate,many-to-one
来源: https://codeday.me/bug/20190520/1143808.html