Home > front end >  How to return just a single field of a collection using JPQL?
How to return just a single field of a collection using JPQL?

Time:12-07

In my database I have software packages and those software packages have maintainers. Now I'd like to return just the maintainers' names for a given software package. Package and Maintainer have a ManyToMany association.

I've tried several things but didn't really succeed.

This returns the whole Maintainer entity that I currently use.

select p.maintainers from Package p where p.name = :name

However in the end I'm only interested in the names and I think there must be a way to directly return a Set<String> from the query. Currently I'm doing this in code.

var maintainers = repo.findMaintainersByPackageName(name);
return maintainers.stream().map(m -> m.getName()).collect(Collectors.toSet());

Here's what I've tried.

select p.maintainers.name from Package p where p.name = :name

That results in an error

org.hibernate.QueryException: illegal attempt to dereference collection

I also tried coming from the other side.

select m.name from Maintainer m where m.packages.name = :name

Unfortunately I also get an error

org.hibernate.QueryException: illegal attempt to dereference collection

So basically the question is, how do I return a single field of a collection in jpql? I'm a bit lost.

Thank you very much!

CodePudding user response:

you should use INNER JOIN in your JPQL. something like

"select m.name from Maintainer m INNER JOIN m.packages p where p.name = :name"
  • Related