Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null vs empty collections in Hibernate

Tags:

java

hibernate

Say I have the following Hibernate-mapped class:

public class ClassA {       
   @OneToMany(fetch=EAGER)
   private List<ClassB> bList;
}

When I read an object of ClassA from a Hibernate session, the bList field is initialized with a PersistentList object, as expected.

I find myself with a requirement where in situations where the list is empty, I need Hibernate to initialize the bList field to null, rather than with an empty PersistentList. In theory, Hibernate has the information it needs to do this, since the fetch on the list is eager. The problem is that according to section 6.1 of the Hibernate docs:

Collection-valued properties do not support null value semantics because Hibernate does not distinguish between a null collection reference and an empty collection.

This makes perfect sense, but I'm hoping someone can come up with a cunning ruse to overcome this limitation. I'm thinking perhaps some listener/callback mechanism might allow me to replace empty lists with null references.

like image 962
skaffman Avatar asked Sep 21 '09 14:09

skaffman


People also ask

Is Empty list same as null?

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.

What is empty collection in stack?

Stack empty() Method in Java Stack. empty() method in Java is used to check whether a stack is empty or not. The method is of boolean type and returns true if the stack is empty else false. Syntax: STACK.empty()


2 Answers

Have you tried to check in the getbList() method? You could do:

if(bList.isEmpty()) 
    return null;
return bList;

Hibernate will always create an object for your references, but you are allowed to control the data inside of the getter and setters. If the list has 0 elements you can always return null.

like image 156
amischiefr Avatar answered Oct 08 '22 18:10

amischiefr


I'm curious why you consider this a "limitation' - does a null bList actually have a different meaning to your application than an empty bList?

I think that in most areas, a null collection and an empty collection have the same semantic meaning, which I would guess is why the Hibernate developers sought to limit Hibernate to only using one. Doesn't make much sense to always check if (bList == null || bList.isEmpty) if the two always end up meaning the same thing.

like image 24
matt b Avatar answered Oct 08 '22 19:10

matt b