rioubenson rioubenson - 1 year ago 60
Java Question

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:

Object 1:

public class Person {

@Column(length = 50)
protected String name;

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

...all the getters and setters...

Object 2:

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

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

@Column(precision = 15, scale = 0)
protected long exampleFieldId; 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?


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download