-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Many-to-one-or-zero - to reference a possibly null entity
PostPosted: Thu Feb 09, 2006 6:45 am 
Newbie

Joined: Fri Nov 04, 2005 4:47 am
Posts: 14
Hibernate version: 3.1.2

I'm trying to make an association that is optional, i.e. class A may reference an instance of B, but the reference may also be null.

The assocation is declared as:

Code:
<many-to-one name="exampleProject" class="Project" column="example_project" outer-join="true" not-null="false"/>


But this is causing a NullPointerException when fetching the object having this association.

Is there some way of declaring [many|one]-to-one-or-zero that I don't know about? The only other solution I can imagine is use a collection association as the collection can be empty, but that's not a very satisfactory solution.

[/code]


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 09, 2006 7:01 pm 
Expert
Expert

Joined: Thu Dec 23, 2004 9:08 pm
Posts: 2008
Hibernate will not create any rows for an empty collection, and for a relational database, this is the same as many-to-one-or-none. This tricky bit is that hibernate will call setCollection(null) when loading that empty collection, and this causes a null pointer exception when an internal hash code is being calculated. Put code in you getCollection (or setCollection) method that ensures that your collection object is never null:
Code:
public Set getCollection() {
  if (m_collection == null)
  {
    m_collection = new HashSet();
  }
  return m_collection;
}
If you're using field access, you'll have to put this in the set method. For property access (the default) you can put it in either.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.