{"id":3900,"date":"2020-07-01T18:23:25","date_gmt":"2020-07-01T12:53:25","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=3900"},"modified":"2020-07-01T18:23:27","modified_gmt":"2020-07-01T12:53:27","slug":"hibernate-query-language","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/hibernate-query-language\/","title":{"rendered":"Hibernate Query Language"},"content":{"rendered":"\n<p>Hibernate Query Language is a Hibernate framework <a href=\"https:\/\/en.wikipedia.org\/wiki\/Object_Query_Language\" rel=\"nofollow noopener\" target=\"_blank\">object-oriented query language<\/a>. It is in general similar to SQL but operates not on tables and columns, but with persistent objects and properties of persistent objects. HQL queries are translated under the hood into conventional SQL queries and that performs actions on the database.<\/p>\n\n\n\n<p>You can use SQL statements in the Hibernate framework, but you will need to use Native SQL. So, it can cause database portability hassles. Therefore, it is recommended to use HQL whenever possible and to take advantage of Hibernate SQL generation and caching strategies.<\/p>\n\n\n\n<p>In HQL keywords (SELECT, FROM, WHERE, etc.) are not case sensitive. But, table and column names are case sensitive in HQL. For example, that FrOm can be written as fRoM or just FROM. But,&nbsp; edu.hibernate.test.FOO cannot be replaced with edu.hibernate.test.Foo.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>The FROM clause<\/strong><\/h3>\n\n\n\n<p>The FROM clause is used to load a complete persistent object into memory. Let&#8217;s look at code snippet to understand how to call the HQL query and how the simplest query with the FROM clause looks like. We will use the User class. It is valuable to mention that we do not usually need to qualify the class name with its package name because auto-import is the default. We don&#8217;t need to write &#8220;FROM edu.test.User&#8221;. Simple &#8220;FROM User&#8221; is enough.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>import<\/strong> java.util.List;\n<strong>import<\/strong> org.hibernate.Session;\n<strong>import<\/strong> org.hibernate.cfg.Configuration;\n\n<strong>public<\/strong> <strong>class<\/strong> HibernateExample {\n\n<strong>public<\/strong> <strong>static<\/strong> <strong>void<\/strong> main(String[] args)&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Configuration configuration = <strong>new<\/strong> Configuration();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;configuration.addAnnotatedClass(edu.hibernate.example.User.<strong>class<\/strong>);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Session session = configuration.configure().buildSessionFactory().openSession();&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String hql = \"FROM User\";\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List results = session.createQuery(hql).getResultList();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}\n<\/pre>\n\n\n\n<p>It is possible to use aliases. For example, &#8220;from User as userEntity&#8221;. You could also write:&nbsp; &#8220;from User userEntity&#8221;. In the FROM clause you can use multiple tables. In the case of multiple classes, the result will be in a cartesian product or &#8220;cross&#8221; join:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">FROM User, Car<br>FROM User as user, Car as car<\/pre>\n\n\n\n<p>The query &#8220;FROM User as user&#8221; returns instances not only of User but also of subclasses (e.g.: FacebookUser, InstaUser). HQL queries use any Java class or interface in the FROM clause. In this case, it will return the list of instances of all classes that extend that class or implement the interface.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>SELECT Clause<\/strong><\/h3>\n\n\n\n<p>The SELECT clause gives the developer more control over the result. With this clause, you can obtain just several properties of objects instead of the entire object. The syntax is simple. Let&#8217;s get just the first_name field from the User object. The User.firstName is a property of User object rather than a field of the User table.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>import<\/strong> java.util.List;\n<strong>import<\/strong> org.hibernate.Session;\n<strong>import<\/strong> org.hibernate.cfg.Configuration;\n\n<strong>public<\/strong> <strong>class<\/strong> HibernateExample {\n\n<strong>public<\/strong> <strong>static<\/strong> <strong>void<\/strong> main(String[] args)&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Configuration configuration = <strong>new<\/strong> Configuration();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;configuration.addAnnotatedClass(edu.hibernate.example.User.<strong>class<\/strong>);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Session session = configuration.configure().buildSessionFactory().openSession();&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String hql = \"SELECT U.firstName FROM User U\";\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List results = session.createQuery(hql).getResultList();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>WHERE Clause<\/strong><\/h3>\n\n\n\n<p>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&#8217;s create a simple example.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>import<\/strong> java.util.List;\n<strong>import<\/strong> org.hibernate.Session;\n<strong>import<\/strong> org.hibernate.cfg.Configuration;\n\n<strong>public<\/strong> <strong>class<\/strong> HibernateExample {\n\n<strong>public<\/strong> <strong>static<\/strong> <strong>void<\/strong> main(String[] args)&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Configuration configuration = <strong>new<\/strong> Configuration();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;configuration.addAnnotatedClass(edu.hibernate.example.User.<strong>class<\/strong>);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Session session = configuration.configure().buildSessionFactory().openSession();&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String hql = \"FROM User U WHERE U.id = 4\";\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List results = session.createQuery(hql).getResultList();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}\n<\/pre>\n\n\n\n<p><strong>Expressions<\/strong><\/p>\n\n\n\n<p>HQL supports the list of expressions that are used in the where clause:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>math operators: +, -, *, \/<\/li><li><a href=\"https:\/\/www.h2kinfosys.com\/blog\/control-statements-in-java\/\">comparison operators<\/a>: =, >=, &lt;=, &lt;>, !=, like<\/li><li>logical operations: and, or, not<\/li><li>is empty, is not empty, in, not in, between, is null, is not null, member of and not member of<\/li><li>string concatenation concat(&#8230;,&#8230;)<\/li><li>current_date(), current_time(), and current_timestamp()<\/li><li>second(&#8230;), minute(&#8230;), hour(&#8230;), day(&#8230;), month(&#8230;), and year(&#8230;)<\/li><li>substring(), trim(), lower(), upper(), length(), abs(), sqrt(), mod()<\/li><li>str() for converting values to a readable string<\/li><li>for collection-valued path expressions: size(), minelement(), maxelement(), minindex(), maxindex()<\/li><li>scalar function like sign(), trunc(), rtrim(), and sin()<\/li><li>named parameters :name, :start_date, and :x1<\/li><li>SQL literals &#8216;foo&#8217;, 69, 6.66E+2, &#8216;1970-01-01 10:00:01.0&#8217;<\/li><li>Java public static final constants eg.Color.TABBY<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>ORDER BY Clause<\/strong><\/h3>\n\n\n\n<p>ORDER BY Clause is used to sort your results after calling the HQL query. It is possible to order the result set in an ascending (ASC) or descending (DESC) way. You can sort your result by any property on the objects. For example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"FROM User U WHERE U.id &lt; 10 ORDER BY U.id DESC\";\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0List results = session.createQuery(hql).getResultList();<code>\u00a0<\/code><\/pre>\n\n\n\n<p>It can turn out that we need to sort a result set by more than one property. It is possible in HQL. We just need to add the additional properties separated by commas to the end of the ORDER BY clause.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"FROM User U WHERE U.id &lt; 10 ORDER BY U.id DESC, U.firstname DESC\";\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0List results = session.createQuery(hql).getResultList();<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>GROUP BY Clause<\/strong><\/h3>\n\n\n\n<p>GROUP BY Clause allows you to pull information from the database and group it based on an attribute value. It uses the result to include an aggregate value. Let&#8217;s create a simple example of the use of the GROUP BY Clause.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"SELECT MAX(U.age), U.firtName FROM User U GROUP BY U.firstName\";\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0List results = session.createQuery(hql).getResultList(); \u00a0<\/pre>\n\n\n\n<p>HQL has a list of aggregate methods similar to the SQL. They have the same name and work the same way as corresponding methods in SQL. But HQL is adapting to all database types. Here is the list of the available aggregate methods supported by HQL:<\/p>\n\n\n\n<p><em>avg(property name) <\/em>&#8211; this function finds an average of property values. For example:<\/p>\n\n\n\n<p><em>count(property name or *)<\/em> &#8211; function counts the number of times a property occurs in the results.<\/p>\n\n\n\n<p><em><strong>For example:<\/strong><\/em><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp;String hql = \"SELECT COUNT(*) FROM User U\";\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List results = session.createQuery(hql).getResultList();&nbsp;&nbsp;&nbsp;\n<em>max(property name) -&nbsp; function finds the maximum value of the property values.<\/em><\/pre>\n\n\n\n<p><em><strong>For example:<\/strong><\/em><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"SELECT MAX(U.age), U.firtName FROM User U GROUP BY U.firstName\";\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List results = session.createQuery(hql).getResultList();&nbsp;&nbsp;\n\n<em>min(property name)<\/em> - the function finds the minimum value of the property values<\/pre>\n\n\n\n<p><strong><em>Foe example:<\/em><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp;String hql = \"SELECT MIN(U.age) FROM User U\";\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List results = session.createQuery(hql).getResultList();&nbsp;&nbsp;\n<em>sum(property name) <\/em>- the function that sums the total of the property values.\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String hql = \"SELECT SUM(U.salary) FROM User\";\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List results = session.createQuery(hql).getResultList();&nbsp;<\/pre>\n\n\n\n<p>In HSL there is also a keyword distinct that counts just the unique values in the row set. Here is an example that where the query will return a unique firstnames count:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"SELECT count(distinct U.firstName) FROM User U\";\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List results = session.createQuery(hql).getResultList();\n<\/pre>\n\n\n\n<p><strong>Using Named Parameters<\/strong><\/p>\n\n\n\n<p>It is possible in Hibernate to use named parameters in HQL queries. This is good because we can write&nbsp; HQL queries that accept user input. And we do not need to defend against SQL injection attacks. Here is an example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"FROM User U WHERE U.id = :user_id\";\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List results = session.createQuery(hql).setParameter(\"user_id\",4).getResultList();<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>UPDATE Clause<\/strong><\/h3>\n\n\n\n<p>HQL supports bulk updates. Therefore, the UPDATE clause can be used to update one or more properties of one or more objects. Let&#8217;s look at the example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"UPDATE User set age = :age \" + \"WHERE id = :user_id\";\nQuery query = session.createQuery(hql);\nquery.setParameter(\"age\", 30);\nquery.setParameter(\"user_id\", 10);\n<strong>int<\/strong> result = query.executeUpdate();\nSystem.<strong><em>out<\/em><\/strong>.println(\"Rows affected: \" + result);<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>DELETE Clause<\/strong><\/h3>\n\n\n\n<p>The DELETE clause is used to delete one or multiple objects.Here is an example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"DELETE from User WHERE id = :user_id\";\nQuery query = session.createQuery(hql);\nquery.setParameter(\"user_id\", 10);\n<strong>int<\/strong> result = query.executeUpdate();\nSystem.<strong><em>out<\/em><\/strong>.println(\"Rows affected: \" + result);<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>INSERT Clause<\/strong><\/h3>\n\n\n\n<p>INSERT INTO clause can only insert values from one object to another object. For example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"INSERT INTO User(firstName, lastName, age)\"\n+ \"SELECT firstName, lastName, aage FROM old_user\";\n<strong>int<\/strong> result = session.createQuery(hql).executeUpdate();\nSystem.<strong><em>out<\/em><\/strong>.println(\"Rows affected: \" + result);\n<\/pre>\n\n\n\n<p><strong>Pagination using Query<\/strong><\/p>\n\n\n\n<p>There are two methods for pagination:<\/p>\n\n\n\n<p>Query setFirstResult(int startPosition) &#8211; method takes an integer that represents the first row in your result set, starting with row 0. For example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"FROM User\";\nQuery query = session.createQuery(hql);\nquery.setFirstResult(1);\nList results = query.list();\n<\/pre>\n\n\n\n<p>Query setMaxResults(int maxResult)- method tells Hibernate to retrieve a fixed number maxResults of objects. Here is an example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"FROM User\";\nQuery query = session.createQuery(hql);\nquery.setMaxResults(5);\nList results = query.list();<\/pre>\n\n\n\n<p>We can also combine both methods:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"FROM User\";\nQuery query = session.createQuery(hql);\nquery.setFirstResult(1);\nquery.setMaxResults(5);\nList results = query.list();<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Associations and joins<\/strong><\/h3>\n\n\n\n<p>HQL supports the same join types as ANSI SQL: inner join, left outer join, right outer join, full join (not usually useful). For example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">String hql = \"from Cat as cat \" +&nbsp;\n\"&nbsp; &nbsp; join cat.mate as mate \" +&nbsp;\n\"&nbsp; &nbsp; left join cat.kittens as kitten\";\nQuery query = session.createQuery(hql);\nList results = query.list();<\/pre>\n\n\n\n<p>HQL supports implicit and explicit association joining.<\/p>\n\n\n\n<p>The queries from the previous example use the explicit form, where the join keyword is explicitly used in the from clause. This form is recommended.<\/p>\n\n\n\n<p>In the implicit form, the join keyword is not used. The association uses dot-notation. Implicit joins can appear in any HQL Clause. For example:<\/p>\n\n\n\n<p>from Cat as cat where cat.mate.name like &#8216;%s%&#8217;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hibernate Query Language is a Hibernate framework object-oriented query language. It is in general similar to SQL but operates not on tables and columns, but with persistent objects and properties of persistent objects. HQL queries are translated under the hood into conventional SQL queries and that performs actions on the database. You can use SQL [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3919,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[1054,1000,1053],"class_list":["post-3900","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-tutorials","tag-from-clause","tag-hibernate-query-language","tag-hql"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/3900","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=3900"}],"version-history":[{"count":0,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/3900\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/3919"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=3900"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=3900"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=3900"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}