digiarnie
digiarnie

Reputation: 23415

Hibernate filter on an entity list but only retrieving one of the attributes

If I have an entity called Foo that looks a little like this:

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

I want to retrieve the names of the Foo objects that have an id greater than 10. If I already have a collection of Foo objects, I could 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 such that I would retrieve a list of Strings (i.e. the Foo names) instead of the list of Foos which I would have to manually filter out like so:

for (Foo foo : filteredFoos) {
    String name = foo.getName();
    ...
}

Upvotes: 3

Views: 4597

Answers (2)

harun ugur
harun ugur

Reputation: 1852

You an use short code for filter to hibernate query like this;

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

Upvotes: 0

Adeel Ansari
Adeel Ansari

Reputation: 39907

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

Or try this. I am not sure if this would work, but the former will work definitely.

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

Upvotes: 1

Related Questions