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.
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
In SELECT statement:
ResultSet rs=st.executeQuery("select * from diet");
Query query= session.createQuery("from diet");
In WHERE statement
ResultSet rs=st.executeQuery("select * from diet where id=301");
Query query= session.createQuery("from diet where id=301 ");
In UPDATE statement
String query = "update User set name=? where id = ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, "diet2");
Query q = session.createQuery("update User set name=:n where id=:i");
int status = q.executeUpdate();
In INSERT statement
String sql = "INSERT INTO Stock VALUES (100, 'abc')";
int result = stmt.executeUpdate(sql);
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.
- HQL is similar to SQL and is also case insensitive.
- 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.
- 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.
- HQL supports concepts like polymorphism, inheritance, association, etc. It is a powerful and easy-to-learn language that makes SQL object oriented.
- 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.