3

this would be my query:

SELECT DISTINCT name FROM city;

this is my code at the moment:

public List<City> listCities() {
    return sessionFactory.getCurrentSession().createQuery("from City").list();
}

which means:

SELECT * FROM city;

How must I change the code, so the query would be correct?

I hope I gave enough information, feel free to ask questions.

Jaanus
  • 16,161
  • 49
  • 147
  • 202

1 Answers1

1

Simply write the following HQL:
sessionFactory.getCurrentSession().createQuery("select distinct from City").list()
or even better (with result transformer):

Query q = sessionFactory.getCurrentSession().createQuery("from City");
q.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
Bivas
  • 1,484
  • 1
  • 11
  • 17
  • 1
    seems reasonable, but don't I have to also include the name of the field I wanna query as `DISTINCT` ? like this `SELECT DISTINCT column_name(s) FROM table_name` – Jaanus Sep 16 '11 at 11:39
  • What would the return type would be when going with second solution? – Jaanus Sep 16 '11 at 14:31
  • SELECT DISTINCT doesn't follow SQL guidelines but HQL one - meaning, distinction is done by id. Return type for the 2nd solution is your City entity. i find the 2nd one better in most cases. – Bivas Sep 18 '11 at 21:11