Open In App

Hibernate Native SQL Query with Example

Last Updated : 19 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads