title: Hibernate: Native SQL query repeating column results
body: <p>I'm experiencing some strange issues when executing the following native SQL query within a Hibernate environment:</p>
  
  <pre><code>public List&lt;Object[]&gt; 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();
  }
  </code></pre>
  
  <p>If you look at the properties that are being returned, you'll notice that there are three <code>description</code> fields from three different tables. The problem that I'm having is that the value of the column <code>a.description</code> is being duplicated in the array positions that should correspond to <code>s.description</code> and <code>q.description</code>. </p>
  
  <p>For example, if I had a result row such as:</p>
  
  <p><code>[1, "Section A", 1, "Question A", 1, 1, "Answer A", 2, 2, 2]</code></p>
  
  <p>Hibernate would return an incorrect <code>Object[]</code> for that row such as:</p>
  
  <p><code>[1, "Answer A", 1, "Answer A", 1, 1, "Answer A", 2, 2, 2]</code></p>
  
  <p>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, <code>a.description</code> 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 <em>Column "description" not found</em>. I'm completely stumped, it is as if the code were mocking me.</p>
  
  <p>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.</p>