The Wayback Machine - https://web.archive.org/web/20240926142946/https://www.geeksforgeeks.org/hibernate-native-sql-query-with-example/
Open In App

Hibernate Native SQL Query with Example

Last Updated : 19 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Hibernate is a popular object-relational mapping (ORM) tool used in Java applications. It allows developers to map Java objects to database tables and perform CRUD (create, read, update, delete) operations on the database without writing SQL queries manually. Native SQL queries are useful when you need to perform complex queries that cannot be expressed using Hibernate’s Query Language (HQL) or Criteria API. Native SQL queries can be used to perform complex joins, aggregate functions, and subqueries. To execute a native SQL query in Hibernate, you need to create an SQLQuery object and set the SQL statement to be executed.

Advantages of using native SQL queries in Hibernate

While Hibernate provides a powerful and easy-to-use ORM framework for accessing relational databases, there are some scenarios where native SQL queries can offer advantages over using the Hibernate Query Language (HQL) or Criteria API. Here are some advantages of using native SQL queries in Hibernate:

  1. Performance: Native SQL queries can be optimized for performance and may outperform HQL queries or Criteria queries in some cases. This is because native SQL queries are executed directly by the database, bypassing the Hibernate framework and any overhead that it may introduce.
  2. Complex queries: Native SQL queries can handle complex queries that are difficult or impossible to express using HQL or the Criteria API. For example, queries involving complex joins or subqueries can be expressed more easily and efficiently using native SQL.
  3. Integration with legacy systems: In some cases, legacy systems may require the use of native SQL queries to access the database. By providing support for native SQL queries, Hibernate can integrate more easily with legacy systems and allow them to be modernized more gradually.
  4. Access to database-specific features: Native SQL queries allow access to database-specific features that may not be available through Hibernate or JPA. This can include advanced features such as stored procedures, triggers, or custom data types.
  5. Familiarity with SQL: Many developers are familiar with SQL and may prefer to use native SQL queries to express their queries in a more familiar syntax. This can make the code easier to read and maintain, especially for developers who are new to Hibernate or JPA.

JPA Native Query vs Hibernate Native Query

  • Both JPA and Hibernate provide support for executing native SQL queries. However, there are some differences between JPA native queries and Hibernate native queries.
  • JPA (Java Persistence API) is a specification for ORM (Object-Relational Mapping) frameworks in Java, while Hibernate is an implementation of the JPA specification. Both JPA and Hibernate provide support for executing native SQL queries, but there are some differences between the two.

JPA Native Query

  1. The JPA specification defines a set of interfaces for executing native SQL queries, including the EntityManager interface and the Query interface.
  2. Native queries in JPA are created using the createNativeQuery() method of the EntityManager interface, which returns an instance of the Query interface.
  3. JPA Native Query allows developers to map the result set of the query to entities using the addEntity() method or to non-entity classes using the setResultTransformer() method.
  4. JPA Native Query does not provide support for Hibernate-specific features, such as the ability to map the result set of a query to a non-entity class using the addScalar() method.

Hibernate Native Query

  1. Hibernate provides its own implementation of native SQL queries, which includes additional features not found in the JPA specification.
  2. Hibernate Native Query is created using the createSQLQuery() method of the Session interface, which returns an instance of the SQLQuery interface.
  3. Hibernate Native Query provides support for additional mapping options, including the ability to map the result set of a query to a non-entity class using the addScalar() method.
  4. Hibernate Native Query also provides additional methods for controlling the caching behavior of the query, including setCacheable(), setCacheRegion(), and setCacheMode().

Writing and Executing native SQL queries in Hibernate

1. Create a Hibernate Session

The first step is to obtain a Hibernate Session object. This can be done using the SessionFactory, as shown in the following code snippet:

Java




SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();


2. Create a Native Query

Once you have obtained a Hibernate Session, you can create a native SQL query using the createSQLQuery() method, as shown in the following code snippet:

Java




String sqlQuery = "SELECT * FROM customers WHERE last_name = :lastName";
SQLQuery query = session.createSQLQuery(sqlQuery);


3. Set Parameters

If your query includes parameters, you can set their values using the setParameter() method, as shown in the following code snippet:

Java




query.setParameter("lastName", "Smith");


4. Execute the Query

Once you have created and configured your native SQL query, you can execute it using the list() or uniqueResult() methods, as shown in the following code snippet:

Java




List<Customer> customers = query.list();


5. Close the Session

Finally, once you have finished using the Hibernate Session and the results of your query, you should close the Session to release any resources it is holding, as shown in the following code snippet:

Java




session.close();


Debugging Native SQL Queries in Hibernate

Debugging native SQL queries in Hibernate can be done in several ways. Here are some tips to help you debug native SQL queries in Hibernate:

1. Print the generated SQL query

Hibernate generates the SQL query based on the HQL or native SQL query that you write. You can print the generated SQL query to the console to see how Hibernate has transformed your query. You can do this by enabling the Hibernate show_sql property in your configuration file, as shown below:

Java




<property name="hibernate.show_sql">true</property>


2. Use logging to track SQL queries

Hibernate provides a logging facility that you can use to track SQL queries. You can enable logging for SQL queries by setting the Hibernate logging level to debug or trace, as shown below:

Java




<logger name="org.hibernate.SQL" level="debug"/>


3. Check for syntax errors

Native SQL queries are prone to syntax errors, just like any other SQL query. If you encounter errors when executing your native SQL query, make sure to check for syntax errors in the query.

4. Check for mapping errors

If you are mapping the results of a native SQL query to entities or non-entity classes, make sure that the mapping is correct. Any errors in the mapping can cause the query to fail or return unexpected results.

5. Use a debugger

If you are still having trouble debugging your native SQL query, you can use a debugger to step through the code and see where the query is failing. Set breakpoints in your code and step through it to see where the query is failing or returning unexpected results.

Conclusion

  • In conclusion, native SQL queries in Hibernate can be a powerful tool for working with your database when the Hibernate Query Language (HQL) is not flexible enough or efficient enough for your needs. Native SQL queries allow you to write SQL queries directly against your database while still taking advantage of Hibernate’s features, such as caching and lazy loading.
  • However, it’s important to use native SQL queries carefully and only when necessary, as they can be less portable and more error-prone than HQL queries. It’s also important to properly debug and optimize native SQL queries to ensure that they perform efficiently and return the expected results.
  • When writing native SQL queries in Hibernate, you can use the createSQLQuery() method to create a query object, set parameters using the setParameter() method, execute the query using the list() or uniqueResult() methods, and close the Hibernate Session when finished.
  • Overall, native SQL queries can be a useful addition to your toolkit when working with Hibernate but should be used judiciously and with care to avoid potential pitfalls.


Previous Article
Next Article

Similar Reads

Hibernate - Create Hibernate Configuration File with the Help of Plugin
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persisten
3 min read
Hibernate - Native SQL
Hibernate by means of a Native SQL facility, can directly interact with the database like MySQL, Oracle, etc., and all the database-specific queries can be executed via this facility. This feature is much useful if the application is an old application and running for a long time. All of a sudden we cannot bring back new changes but instead with Na
8 min read
Spring Boot JPA Native Query with Example
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any Java object directly into a database table. A native query is a SQL statement that is specific to a particular database like MySQL. It varies a litt
7 min read
Hibernate - Query Language
polymorphicHibernate is a Java framework that makes it easier to create database-interactive Java applications. In HQL, instead of a table name, it uses a class name. As a result, it is a query language that is database-independent. Hibernate converts HQL queries into SQL queries, which are used to perform database actions. Although Native SQL may
4 min read
Hibernate - Cache Eviction with Example
Caching in Hibernate means storing and reusing frequently used data to speed up your application. There are two kinds of caching: Session-level and SessionFactory-level. Level 1 cache is a cache that stores objects that have been queried and persist to the current session. This cache helps to reduce the number of database round trips by storing obj
9 min read
Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XM
6 min read
Hibernate - Table Per Subclass Example using XML File
In Table Per Subclass, subclass tables are mapped to the Parent class table by primary key and foreign key relationship. In a Table per Subclass strategy : For each class of hierarchy there exist a separate table in the database.While creating the database tables foreign key relationship is required between the parent table and the child table.To p
5 min read
Hibernate Example without IDE
Hibernate is a powerful tool used to build applications that need to interact with a database. It is a Java framework that implements the ORM(Object Relational Mapping) technique. What is ORM? ORM stands for Object Relational Mapping. It is a technique that is used to make Java objects persistent by mapping them into a relational database. It simpl
3 min read
Spring ORM Example using Hibernate
Spring ORM is a module of the Java Spring framework used to implement the ORM(Object Relational Mapping) Technique. It can be integrated with various mapping and persistence frameworks like Hibernate, Oracle Toplink, iBatis, etc. for database access and manipulation. This article covers an example of the integration of the Spring ORM module with Hi
5 min read
Hibernate - @Version Annotation with Example
@Version annotation is used to specify the version number for a specific entity. Version Number provided using @Version annotation is used to prevent concurrent modification to an entity. When an entity is being updated, the version number is also incremented. If another transaction tries to update the same entity with the older version number, an
3 min read
Hibernate - @Transient Annotation with Example
@Transient annotation in Hibernate is used to mark a property or field in an entity class as transient. This means that the field or property marked as transient should be excluded when the data persists in the database. Wherever an entity is mapped to a database table, by default all the non-transient fields and properties are persisted. There are
4 min read
Hibernate - @OrderBy Annotation with Example
@OrderBy annotation is used in Hibernate to specify the ordering of the elements in the collection valued property of an entity class. It is used to define the order of the elements which should be displayed. We can order the data within the entity using a specific parameter in ascending or descending order. Examples of @OrderBy AnnotationExample 1
4 min read
Spring MVC and Hibernate CRUD Example
In this article, we will be developing CRUD operations in Spring MVC and Hibernate. Hibernate is an object-relational mapping (ORM) framework. Developers use Hibernate to interact with databases using Java objects rather than SQL queries. Spring MVC is a Model-View-Controller (MVC) framework used to build web applications in Java. The Spring MVC pa
6 min read
Hibernate Example using JPA and MySQL
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a Java framework that is used to develop persisten
4 min read
Hibernate - SQL Dialects
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
3 min read
Show SQL from Spring Data JPA/Hibernate in Spring Boot
In Spring Boot, Spring Data JPA is part of the larger Spring Data Project that can simplify the development of the data access layers in the spring applications using the Java Persistence API and it can provide a higher-level abstraction over the JPA API. It can reduce the boilerplate code and make it easier to work with the database. Spring Data J
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Query String and Query Parameter in Spring MVC
According to Wikipedia "A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a page, or jumping to positions in multimedia content."
6 min read
Java Native Interface with Example
In the Programming World, it is often seen in the comparison of Java vs C/C++. Although the comparison doesn't make any such sense, as both the languages have their Pros and Cons, but what if we can use multiple languages in a single Program? In this article, we will learn How to use JNI(Java Native Interface) to run multiple languages in a single
4 min read
Hibernate - Annotations
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and f
7 min read
Introduction to Hibernate Framework
Prerequisite : JDBC Need of Hibernate Framework Hibernate is used to overcome the limitations of JDBC like: JDBC code is dependent upon the Database software being used i.e. our persistence logic is dependent, because of using JDBC. Here we are inserting a record into Employee table but our query is Database software-dependent i.e. Here we are usin
4 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question has 4 solutions. Via Bag Mapping, in Hibernate, w
4 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let's understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate. Before getting into the difference
2 min read
Hibernate Lifecycle
Here we will learn about Hibernate Lifecycle or in other words, we can say that we will learn about the lifecycle of the mapped instances of the entity/object classes in hibernate. In Hibernate, we can either create a new object of an entity and store it into the database, or we can fetch the existing data of an entity from the database. These enti
4 min read
Java - JPA vs Hibernate
JPA stands for Java Persistence API (Application Programming Interface). It was initially released on 11 May 2006. It is a Java specification that gives some functionality and standard to ORM tools. It is used to examine, control, and persist data between Java objects and relational databases. It is observed as a standard technique for Object Relat
4 min read
Spring Boot - Integrating Hibernate and JPA
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Hibernate - Difference Between ORM and JDBC
Hibernate is a framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic that is independent of database software. ORM (Object-Relational Mapping) ORM, an abbreviation for Ob
4 min read
Hibernate - Generator Classes
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas in Hibernate framework we use Objects to develop persistence logic that is independent of
5 min read
Hibernate - Create POJO Classes
POJO stands for Plain Old Java Object. In simple terms, we use POJO to make a programming model for declaring object entities. The classes are simple to use and do not have any restrictions as compared to Java Beans. To read about POJO classes and Java Bean refer to the following article - POJO classes and Java Bean POJO is handier as its best in r
3 min read
Hibernate - One-to-One Mapping
Prerequisite: Basic knowledge of hibernate framework, Knowledge about databases, Java Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to
15 min read
Article Tags :
Practice Tags :