whirlwin
whirlwin

Reputation: 16521

Find object(s) by arbitrary attributes in Hibernate

I am relatively new to Hibernate (4) and ORMs in general, and would like to know which is the easiest or most convenient way to find object(s) by attributes.

class Foo {

    private Long id;

    private String name;

    private Integer age;

    private Integer favoriteNumber;

    private String catchphrase;

}

Say I have an instance of Foo, the attributes are set arbitrarily, or in other words, I do not know which attributes are set (id might not have been set).

Based on the attributes that are not null, I would like to find any matching object(s) from the database.

Ideally I would want to use a method like this:

session.getCurrentSession().find(foo); which returns a list of Foo.

PS. I do not want to use reflection to accomplish this!

Upvotes: 3

Views: 5403

Answers (1)

dcernahoschi
dcernahoschi

Reputation: 15240

The best approach to your use case is to use a query by example:

session.getCurrentSession()
     .createCriteria(Foo.class).add(Example.create(foo)).list();

UPDATE: Querying by example doesn't include the id attribute in the search. I assumed here that you are not interested in a query by id. If you know the id and you are interested by a query by id you need to do a separate:

(Foo) session.getCurrentSession().get(Foo.class, fooId);

Upvotes: 5

Related Questions