Java – Hibernate Query API and Java 1.5/Generics

genericshibernatejava

All APIs in Hibernate are from 1.4 and are thus not using java generics.

So I wonder how "safe" the following is: (preconditions: name column is of datatype String, or atleast compatible to String)

@SuppressWarnings("unchecked")
public List<String> getAll() {
    Query q = session.createQuery(
        "select name from Customers");
    return q.list();    
}

From the Queryi API (org.hibernate.Query.list()) javadoc.

"Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[]. "

Best Solution

It'll be safe as long as you are sure that the query does not "contain multiple results per row". (I'm not familiar with queries, so I am unsure whether it can happen in this case.) If a row does contain multiple results, then when you try to access it, it will throw ClassCastException at runtime because that element will be an Object[] object instead of a String object.