Avoid populating Collections with null values in GroupBy projections #259

Closed
jmiguelsamper opened this Issue Oct 29, 2012 · 3 comments

Comments

Projects
None yet
2 participants
@jmiguelsamper

A query with a LEFT JOIN and GroupBy.list GroupExpression produces lists with size 1 and a NULL element inside.

Following the documentation example with Cat and Kitten there would be the following class

@Entity
public class Cat {
     ...
     Integer id;
     String name;
     List<Kitten> kittens;
     ...
}

And the query would be like

      QCat cat = QCat.cat;
      QKitten kitten = new QKitten("kitten");
      query = query.from(cat);
      query = query.leftJoin(cat.kittens, kitten);
      query.transform(GroupBy.groupBy(cat.id).as(
           ConstructorExpression.create(
                CatView.class, cat.id, cat.name, GroupBy.list(kitten))
      ));

This works OK when a cat has kittens, but if a cat has no kittens the kitten list is a List with size 1 and a single null element inside.

Maybe this is not the most coherent behavoir, as a LEFT JOIN in JPA would set the kittens field as null.

The issue could be worked-around by reimplementing GList with the following modifications:

        @Override
        public void add(T o) {
            if (o != null) {
                list.add(o);
            }
        }

        @Override
        public List<T> get() {
            if (list.isEmpty()) {
                return null;
            } else {
                return list;
            }
        }

I suppose the GSet and GMap classes have the same behavoir.

@timowest

This comment has been minimized.

Show comment
Hide comment
@timowest

timowest Oct 30, 2012

Member

Returning null collections is considered an anti pattern, so I didn't do any change to the get() implementations, but add implementations work now as you suggested.

Member

timowest commented Oct 30, 2012

Returning null collections is considered an anti pattern, so I didn't do any change to the get() implementations, but add implementations work now as you suggested.

@timowest

This comment has been minimized.

Show comment
Hide comment
@timowest

timowest Oct 30, 2012

Member

Released in 2.8.2

Member

timowest commented Oct 30, 2012

Released in 2.8.2

@timowest timowest closed this Oct 30, 2012

@jmiguelsamper

This comment has been minimized.

Show comment
Hide comment
@jmiguelsamper

jmiguelsamper Oct 30, 2012

You're right, returning empty collections is a better option.

You're right, returning empty collections is a better option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment