rioubenson
rioubenson

Reputation: 401

Does Hibernate always load associated object even if it can be null?

I have a question regarding Hibernate.

I have two objects with a Many-to-One relationship:

Eg: Object 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...
 }

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

I have tried to make this example as simple as possible. My issue is that the associated object (Group) on Person can be null. Currently, Hibernate loads up an instance of Group when I load up a particular Person and throws an exception because it cannot set exampleFieldId to be null (as it is a primitive type).

I can stop this error by changing long to be Long however, I would have thought that the Group object on Person should be null and thus no Group object loaded in the first place?

Does anyone know if Hibernate loads the associated object regardless of it being allowed to be null, or have I missed some important annotation?

Thanks

Upvotes: 5

Views: 1892

Answers (2)

Tony Day
Tony Day

Reputation: 2170

As mentioned by 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

This seems to be the same issue you are experiencing even though it is in NHibernate. Worth checking though!

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

Edit: It could be that you're missing @Fetch(FetchMode.JOIN).

Upvotes: 5

rioubenson
rioubenson

Reputation: 401

I have finally worked out what was going on here, and the issue was not with Hibernate.

Deep in the code I had a UserType that converted a null String into a empty String, meaning that the groupCode would never actually be null. Hence Hibernate assumes that there is a child object to load.

Adding the annotation @Type(type="org.hibernate.type.StringType") above the groupCode avoided this issue.

Interestingly I had misunderstood the use of @NotFound(action=NotFoundAction.IGNORE).

I had thought it was used to solve the issue I described above, but it actually defines what to do if groupCode is set but there’s no corresponding Group; not what to do when groupCode is null.

Others may fall for that too.

Upvotes: 0

Related Questions