The benefits of an ORM are that I can map database tables to Java objects. If I use HQL to write custom statements then what's the point? I may as well write normal SQL queries and use ResultSets?
-
2SQL retrieves rows. HQL retrieves entites/objects, doing all the work for you. – Sotirios Delimanolis Jan 31 '14 at 16:25
-
If I write my own HQL and retrieve a column that's the result of the calculation: `table.a column.a - table.b column.b` then I have a column that cannot be mapped because it's a customized result? – Jan 31 '14 at 16:27
-
Depending on the result of the operation, Hibernate will map it to some `Object` sub type, maybe an `Integer` or a `Long`. – Sotirios Delimanolis Jan 31 '14 at 16:28
-
Which is the equivalent of `resultSet.getInteger(...)` right? – Jan 31 '14 at 16:29
-
Something like that. I don't know the internal implementation that Hibernate uses. You can always use native queries – Sotirios Delimanolis Jan 31 '14 at 16:31
2 Answers
Well, basically because sometimes it is impossible (or very hard) to write queries using the other alternatives. Then you need to fallback to the HQL alternative.
HQL has, as disadvantage, the fact that you write strings with it. So it is highly recommended other strategies. But, sometimes, it is the fastest way to implement it.
I would also say for you to read this post, which was extensively discussed about HQL already: JPA and Hibernate - Criteria vs. JPQL or HQL

- 1
- 1

- 841
- 7
- 17
HQL is the only alternative get out the little bit performace left in hibernate.
If you have a big table with many rows and all you need is the id and a description, then you are better of with hql. You can fill a pojo the two column information and if you are using hibernate 4, you have some sort of type safty too.
query:
final TypedQuery<Pojo> query = em.createQuery(new StringBuilder()
.append("SELECT new ").append(Pojo.class.getName())
.append("(tbl.id, tbl.desc) FROM ")
.append(BigTable.class.getName()).append(" tbl ")
.append("WHERE tbl.id between :start and :end ")
.toString(),
Pojo.class
);
List<Pojo> list = query.getResultList();

- 2,018
- 25
- 32