Where it is better to initialize Foo's Set?
Most of time, I initialize a collections when declaring it, which is what Hibernate recommends. Quoting the documentation:
Hibernate requires that persistent
collection-valued fields be declared
as an interface type. For example:
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; }
}
The actual interface might be
java.util.Set
,
java.util.Collection
,
java.util.List
, java.util.Map
,
java.util.SortedSet
,
java.util.SortedMap
or anything you
like ("anything you like" means you
will have to write an implementation
of
org.hibernate.usertype.UserCollectionType
.)
Notice how the instance variable was
initialized with an instance of
HashSet
. This is the best way to
initialize collection valued
properties of newly instantiated
(non-persistent) instances. When you
make the instance persistent, by
calling persist()
for example,
Hibernate will actually replace the
HashSet
with an instance of
Hibernate's own implementation of
Set
.
If leaving it null
is part of your business, my suggestion would be to initialize it in a (common) link management methods:
public class Foo {
...
private Set<Bar> bars;
...
public void addBar(Bar bar) {
if (this.bars == null) {
this.bars = new HashSet<Bar>();
}
this.bars.add(bar);
}
}
What specific Sets and Lists are better for such purposes?
It all depends on the semantics you need. A Set
doesn't allow duplicates, a List
allows duplicates and introduces positional indexing.
What conceptual issues has my current implementation, and how to do better?
- I wouldn't perform an assignment in the getter.
- If a collection is supposed to be
null
at that point, let it be null
.
- I don't see the added value of your service
- why not just calling
foo.getBars()
?
- why converting the collection?