-->
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: to new or not when comes to association?
PostPosted: Mon Nov 19, 2007 12:13 pm 
Newbie

Joined: Wed Sep 05, 2007 9:26 am
Posts: 16
Hi,

I have some classes/code like this:
public class Item {
private Long id;
private List<Bid> bids;
@Id
@GeneratedValue
public Long getId() {
return id;
}

@OneToMany(cascade= CascadeType.ALL, mappedBy="item")
public List<Bid> getBids() {
return bids;
}
// getter/setters ...
}

public class Bid {
private Long id;
private Item item;

@Id
@GeneratedValue
public Long getId() {
return id;
}

@ManyToOne()
@JoinColumn(name = "item_id")
public Item getItem() {
return item;
}

// getters/setters ...
}

I did not new the instance bids, but why I still can access the elements with following code?

Item item = (Item) _session.load(Item.class, new Long(3));
System.out.println(item.getBids().get(0).getId());
which is correct?
private List<Bid> bids;
or
private List<Bid> bids = new ArrayList<Bid>();

Help me understand this, thanks.

A.C.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Nov 19, 2007 1:06 pm 
Beginner
Beginner

Joined: Mon Feb 19, 2007 4:22 am
Posts: 22
Location: Poland
When you load/get object via Hibernate, it automatically instantiates collections (more precisely: collection references in loaded object are set to Hibernate's own implementations).

If you did this:
Code:
bid item = new Item();
item.getBids().get(0);           // error


this would raise NullPointerException, because, as you said, bids are not instantiated. So, generally, it is wise to instantiate collections, because you probably want to use them, even if they are not managed by Hibernate yet.

Greetings


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.