java – How to deal with a List of Objects after a Hibernate query against a single entity – Education Career Blog

After calling list() on a Hibernate Query which you expect to just return a list of Foo objects (see example below), how best would you deal with this situation?

Query query = session.createQuery("from Foo");
List list = query.list();

I don’t particularly like seeing this:

public List read() { ... }

When I would much prefer:

public List<Foo> read() { ... }

Would you expect callers of the read method to have cast to Foo for each element? Is there a nice way to get the read method to return List< Foo >?

,

Would you expect callers of the read method to have cast to Foo for each element? Is there a nice way to get the read method to return List< Foo >?

No, I wouldn’t expect the caller to do the cast, so I’d write things like this:

Query query = session.createQuery("from Foo");
List<Foo> list = query.list();

And if you want to remove the non type-safe cast warning (the Hibernate Query API is not type-safe):

Query query = session.createQuery("from Foo");
@SuppressWarnings("unchecked")
List<Foo> list = query.list();

Leave a Comment