I was curious about something. Let's say we have a simple relation between Employee and Phone:
@Entity
public class Employee {
@Id
@Column(name="EMP_ID")
private long id;
...
@OneToMany(mappedBy="owner")
private List<Phone> phones;
...
}
@Entity
public class Phone {
@Id
private long id;
...
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="OWNER_ID")
private Employee owner;
...
}
Let's assume that an Employee has no phones, no entries in the Phone table. If I were to have a piece of code that gets the phones of an Employee and iterates over them for whatever reason
for (Phone phone : employee.getPhones())
{
...
}
Would the getter retun NULL or an empty Collection and would the getching strategy play a part.
If I remember correctly, hibernate has its own implementation of collection using proxies and for LAZY fetch, it instantiates with one of those and when needed retrieves the data from the table (correct If I am wrong). So would at the time the getter is called try to retrieve the data from the table, get an empty set as a result and return an empty collection. (This is what I think). Or should I always check if the result of the getter is NULL or not?
An empty collection isn't the same as null . An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.
Empty collection. Always. It is considered a best practice to NEVER return null when returning a collection or enumerable.
Fetch a Single Result If you want to obtain a single Object reference instead of a List, the uniqueResult() method on the Criteria object returns an object or null. If there is more than one result, the uniqueResult() method throws a HibernateException .
Since those collections are lazy by default employee.getPhones()
should return a proxy for that collection (e.g. PersistentList
or similar) which loads the list elements when you access the list.
Additionally, because Phone
is the owner of the relation Hibernate won't know whether there are any phones for an employee or not so it has to assume the list exists - although it might be empty. That said it wouldn't make much sense for Hibernate to return null since:
getPhones()
must not return null but a proxyUsing eager loading shouldn't change that. Hibernate would know that there is no phone for the employee but returning null instead of an empty list, which also would express that there are no phones, would still make little sense (think of allowing to add phones for a loaded employee, differences in code where you'd not need them if null was used for eager fetching, etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With