2

I'm experiencing some strange issues when executing the following native SQL query within a Hibernate environment:

public List<Object[]> getExcelResults(Integer idSurvey)
{
    StringBuffer queryString = new StringBuffer();

    //build query string
    queryString.append("select s.idSection, s.description as sectionDescription, ");
    queryString.append("q.idQuestion, q.description as questionDescription, q.type, ");
    queryString.append("a.idAnswer, a.description, ");
    queryString.append("sum(sa.checked), avg(sa.value), count(sl.idSurveyLog) ");
    queryString.append("from surveylog sl ");
    queryString.append("inner join surveyanswerlog sa ");
    queryString.append("on sl.idSurveyLog = sa.idSurveyLog ");
    queryString.append("inner join answer a ");
    queryString.append("on sa.idAnswer = a.idAnswer ");
    queryString.append("inner join question q ");
    queryString.append("on a.idQuestion = q.idQuestion ");
    queryString.append("inner join section s ");
    queryString.append("on q.idSection = s.idSection ");
    queryString.append("where sl.idSurvey = :idSurvey ");
    queryString.append("group by s.idSection, q.idQuestion, a.idAnswer ");
    queryString.append("order by s.idSection, q.idQuestion, a.idAnswer asc; ");

    //create query
    Query query = this.sessionFactory.getCurrentSession().createSQLQuery(queryString.toString());
    query.setInteger("idSurvey", idSurvey);

    return query.list();
}

If you look at the properties that are being returned, you'll notice that there are three description fields from three different tables. The problem that I'm having is that the value of the column a.description is being duplicated in the array positions that should correspond to s.description and q.description.

For example, if I had a result row such as:

[1, "Section A", 1, "Question A", 1, 1, "Answer A", 2, 2, 2]

Hibernate would return an incorrect Object[] for that row such as:

[1, "Answer A", 1, "Answer A", 1, 1, "Answer A", 2, 2, 2]

At first I thought that I needed to use aliases since all of those columns have the same names, but as you can see from the code above, a.description doesn't have an alias. The reason for this is that, if I add an alias to all three columns, I get a sqlexception which reads Column "description" not found. I'm completely stumped, it is as if the code were mocking me.

Even weirder, if I take the generated SQL query from the console and run on it on MySQL it works fine. I suspect that I might have some sort of typo, but I've been looking at this code for so long that I no longer see anything.

4

1 回答 1

2

您应该addScalar对所有查询投影使用该方法。例如,

  Query query = sessionFactory.getCurrentSession().createSQLQuery(queryString.toString())
    .addScalar("sectionDescription", StandardBasicTypes.STRING)
    .addScalar("questionDescription", StandardBasicTypes.STRING)
    .setInteger("idSurvey", idSurvey);
于 2013-01-09T21:35:50.980 回答