Search code examples
sqlhibernatehqlnativequery

Hibernate, SQL in HQL (NativeQuery)


I am starting out at Hibernate. I am at the point, where I try out SQL in HQL. I saw a code example which I wanted to recreate, but my output ended up being different. To use SQL in HQL, that person said, if you want to only use a couple of columns, you need to use a Map to get certain columns (So I can´t simply use addEntity here). My Student table got sId, sName, sMarks. Now I want to retrieve only the Students names (sName) and their marks (sMarks). The Problem is, that I only get "null" as values for the names and marks whilst the object shows me the proper values:

Console Output: Hibernate: SELECT sName,sMarks FROM student
{SNAME=Nameless fool number 1, SMARKS=65} null : null

The Code:

NativeQuery querySQL2 = session.createNativeQuery("SELECT sName,sMarks "
            +                                   "FROM student");
querySQL2.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List students = querySQL2.getResultList();
for (Object o : students)
{
    System.out.println(o);
    Map m = (Map)o;
    System.out.println(m.get("sName") + " : " + m.get("sMarks"));
}

Why do I get the proper Object with Syso(o) and just null with Syso(m.get("..."))? Thank you in advance!


Solution

  • Actually you already answered your question {SNAME=Nameless fool number 1, SMARKS=65}. Hibernate convert column names to upper case.