Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL vs. SQL / Hibernate netbeans HQL editor

I am teaching my self hibernate, and am quite confused of why i can not just write simple SQL queries.

I find it rather more confusing to use than plain SQL (what I am used to)

PLUS: The NetBeans HQL editor I found pretty annoying, It is harder for me to produce a right query in HQL, then in SQL, and why does the shown SQL differ from actual SQL statements ?

So why use it ? - As it is known that hibernate is very resource extensive, and I believe that hibernate is the reason for our app to running out of memory very often, as during the process of redeploying e.g...

I am very interested in knowing why I should use Hibernate and not plain SQL (mysql) statements !?

And maybe a good link for hibernate queries would be nice ;), I am using this one atm:

  • http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html

But also interested in any good link explaining the setup of the queries, the mapping, underlying construction etc..

Best Regards Alex

like image 794
Alexander Grosse Avatar asked Nov 12 '10 08:11

Alexander Grosse


People also ask

How does Hibernate HQL work?

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.

Does Hql support all operations?

Need of HQLProvides full support for relational operations. It is possible to represent SQL Queries in the form of objects in HQL which uses classes and properties instead of tables and columns. Return results as objects.

Where clause means specific objects that are returned from?

WHERE clause is used to narrow the specific objects that are returned from the database. It works the same as the SQL WHERE clause but operates with class properties rather than fields of a table. Let's create a simple example.


1 Answers

HQL is object oriented and it's done with the purpose of working on the Java objects representing your DB tables. A basic advantage is that you can put placeholders like :orderNumber (using the colon simbol) in the HQL query and replace with the value of a variable. For example:

int orderNumber = 685412;
List<Order> l= 
    session.createQuery("from Order where orderNumber = :orderNumber")
    .setParameter("orderNumber",orderNumber).list();

In this way you can modify orderNumber in a simple way, evoiding the classical

String query = "select * from Order where orderNumber = " + orderNumber + "...";

Morover using MySQL syntax would sometimes turn your code not reusable if you migrate your DB to another DBMS. Anyway I'm still not so convinced about the preference on HQL.

Here you can find the full grammar definition.

like image 59
bluish Avatar answered Sep 28 '22 09:09

bluish