-->
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.  [ 3 posts ] 
Author Message
 Post subject: Collection entity initialization
PostPosted: Tue Mar 24, 2009 9:39 pm 
Newbie

Joined: Sat Mar 31, 2007 2:10 am
Posts: 3
Below is a sample class with one-to-many relationship to Part. My question is when we declare parts attribute as a Set, do we have to initialize it in the declaration (as in line 3)? Why?

Thanks,
Mike


Code:
public class Product {
    private String serialNumber;
    private Set parts = new HashSet();
    public Set getParts() { return parts; }
    void setParts(Set parts) { this.parts = parts; }
    public String getSerialNumber() { return serialNumber; }
    void setSerialNumber(String sn) { serialNumber = sn; }
}


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 25, 2009 4:53 pm 
Senior
Senior

Joined: Tue Aug 01, 2006 9:24 pm
Posts: 120
I am not sure whether you have to with hibernate. But it's a very good practice in java to do so. You always want to avoid returning nulls whenever possible. Actually, I would say never return a null and if you do, you better have a really good reason for it.

_________________
Please rate my replies as I need points for all of my questions also.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 25, 2009 5:16 pm 
Expert
Expert

Joined: Wed Mar 03, 2004 6:35 am
Posts: 1240
Location: Lund, Sweden
Quote:
My question is when we declare parts attribute as a Set, do we have to initialize it in the declaration (as in line 3)?


No you don't have to. But you have to watch out for 'null' in code like:

Code:
product.getParts().add(part);


Personally, I prefer this:

Code:
public Set getParts() {
  if (parts == null) parts = new HashSet();
  return parts;
}


It avoids the creation of a new HashSet that is just replaced by Hibernate in a call to setParts() every time an existing object is loaded from the database. In practice I don't think it matters which method you use, but I would get crazy if I had to check for 'null' every time I wanted to use a collection.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 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:
cron
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.