Hibernate filter in entity list, but only getting one of the attributes

If I have a Foo object that looks something like this:

@Entity
public final class Foo {
    private int id;
    private String name;
    ...
}

I want to get the names of Foo objects with an identifier greater than 10. If I already have a collection of Foo objects, I can do something like this:

List<Foo> foos = ...
Query filter = session.createFilter(foos, "where id > :id");
filter.setInteger("id", 10);
List filteredFoos = filter.list();

Is there a way to create the above filter so that I can get a list of strings (i.e. Foo names) instead of a Foos list that I would have to manually filter out like this:

for (Foo foo : filteredFoos) {
    String name = foo.getName();
    ...
}
+3
source share
2 answers
List filteredFoos = session.createFilter(foos, "where id > :id")
                           .setInteger("id", 10).list();
List filteredFooNames = session.createFilter(filteredFoos, "select name").list();

Or try this one. I'm not sure if this will work, but the former will definitely work.

List filteredFooNames = session.createFilter(foos, "select name where id > :id")
                           .setInteger("id", 10).list();
+1
source

You use a short code for the filter for a sleeping request, for example:

List<Foo> foos = ....;
Integer id = 10;
List filterList = session.createFilter(foos, "where id>: id").setInteger("id",id).list();
Run codeHide result
0

Source: https://habr.com/ru/post/1770653/