DEV Community

Cover image for Hibernate - HQL vs SQL
Yiğit Erkal
Yiğit Erkal

Posted on

Hibernate - HQL vs SQL

Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't depends on the table of the database. Instead of table name, we use class name in HQL. Therefore, it is database independent query language.

Characteristics of HQL

  • Similar to SQL: HQL's syntax is very similar to standard SQL. If you are familiar with SQL then writing HQL would be pretty easy.

  • Fully object-oriented: HQL doesn't use real names of table and columns. It uses class and property names instead. HQL can understand inheritance, polymorphism and association.

  • Reduces the size of queries

Let's see the difference of the syntax 🍎🍏

In SELECT statement:

SQL
ResultSet rs=st.executeQuery("select * from diet");
HQL
Query query= session.createQuery("from diet");

In WHERE statement

SQL
ResultSet rs=st.executeQuery("select * from diet where id=301");
HQL
Query query= session.createQuery("from diet where id=301 ");

In UPDATE statement

SQL
String query = "update User set name=? where id = ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, "diet2");
preparedStmt.setlnt(2, 5);
preparedStmt.executeUpdate();
HQL
Query q = session.createQuery("update User set name=:n where id=:i");
q.setParameter("n", "diet2");
q.setParameter("i",55);
int status = q.executeUpdate();

In INSERT statement

SQL
String sql = "INSERT INTO Stock VALUES (100, 'abc')";
int result = stmt.executeUpdate(sql);
HQL
Query query = session.createQuery("insert into Stock(stock_code,
stock_name) select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();

❗ HQL only support insert from another table so you have to do this by creating and persisting new entity.

To sum up

  1. HQL is similar to SQL and is also case insensitive.
  2. HQL and SQL both fire queries in a database. In the case of HQL, the queries are in the form of objects that are translated to SQL queries in the target database.
  3. SQL works with tables and columns to manipulate the data stored in it while HQL works with classes and their properties to finally be mapped to a table structure in a database.
  4. HQL supports concepts like polymorphism, inheritance, association, etc. It is a powerful and easy-to-learn language that makes SQL object oriented.
  5. SQL lets you modify the data through insert, update, and delete queries. You can add tables, procedures, or views to your database. The permissions on these added objects can be changed.

Top comments (0)