Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid populating Collections with null values in GroupBy projections #259

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

Comments

@jmiguelsamper
Copy link

@jmiguelsamper jmiguelsamper commented Oct 29, 2012

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
Copy link
Member

@timowest 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.

Loading

@timowest
Copy link
Member

@timowest timowest commented Oct 30, 2012

Released in 2.8.2

Loading

@timowest timowest closed this Oct 30, 2012
@jmiguelsamper
Copy link
Author

@jmiguelsamper jmiguelsamper commented Oct 30, 2012

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

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants