Nearby lessons
15 of 19Hibernate - Native SQL Queries
- Understand Hibernate - Native SQL Queries
- See working code examples
- Learn from common mistakes and Q&A
Learn Hibernate - Native SQL Queries step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.
Native SQL Queries
- List<Object[]> list = query.list();
- System.out.println("ENO\tENAME\tESAL\tEADDR");
- System.out.println("---------------------------------");
- for(Object[] val : list) {
- for(Object o: val) {
- System.out.print(o+"\t");
- System.out.println();
e) IN:It will be used along with where clause to specify a list of values inorder to retrive matched results.
Native SQL Queries
f) BETWEEN : It able to specify min value and max value inorder to retrive the results which are between the specified min value and max value.
Native SQL Queries
g) LIKE: It able to provide a particular pattern in HQL query inorder to retrive matched results.
Native SQL Queries
h) IS NULL: It able to retrive all the results from database table w.r.t a particular column whose value is null.
Native SQL Queries
i) IS NOT NULL: It able to retrive all the results from database table w.r.t a particular column whose value is not null.
Parameters
The main intention of parameters in HQL queries is to take dynamic values in HQL queries. In HQL, there are two types of parameters
- Positional parameters
- Named Parameters
Positional parameters
These parameters are represented in the form of '?' in HQL queries. After specifying these parameters in HQL queries we must set values to these parameters, to set values to positional parameters we have to use the following method.
public void setParameter(int param_Index, xxx value) Where param_Index may start with 0. Where xxx may be byte, short, int,....
Note: In JDBC, positional parameter indexes will start from 1 , but, in HQL parameters indexes will start from 0.
Positional parameters
In HQL queries, we are able to provide more than one positional parameter.
Named Parameters
These parameters are represented in the form of ':Param_Name' in HQL queries, after providing named parameters in HQL query we have to set values to named parameters, for this, we have to use the following method.
public void setXXX(String param_name, xxx value) Where xxx may be byte, short, int, String,.....
Note: in HQL queries, we are able to provide more than one named parameters.
Named Parameters
In Hibernate applications we are able to provide both positional parameters and named parameters with in a single HQL query, but, first we have to provide all positional patameters after that only we have to provide named parameters, we must not provide any positional parameter after named parameter.
Named Parameters
If we provide named parameter before positional parameter ion HQL query then we are able to get the following error or Exception.
ERROR: cannot define positional parameter after any named parameters have been defined
Subqueries
Writing a query in another query is called as Sub Query. HQL is supporting sub queries also.
Pagination — form.html
The process of displying results in more than one page is called as Pagination. Displaying 3 results in a page like three pages out of 9 results is called as "Pagination".
We are able to provide Pagination in Hibernate applications by using setFirstResult() and setMaxResult() methods over Query object.
Example:
Pagination — DisplayServlet.java
Pagination — EmployeeService.java
Pagination — HibernateUtil.java
Pagination — Employee.java
Pagination — hibernate.cfg.xml
Pagination — web.xml
Native SQL
In Hibernate applications, by using Session we are able to perform database operations on only single record, but, if we want to perform database operations over multiple records then we have to use HQL, but, HQL is not providing environment for Database dependent native operations.
HQL is is able to provide support for DML[insert, update, delete, select] operations, but, it has not provided environment for DDL[create, alter and drop] queries.
HQL is not supporting stored procedures and functions kind of database dependent native operations.
In Hibernate applications, If we want to perform database operations over multiple records , database dependent native operations like preparing stored procedures, functions and accessing tham and to perform DDL operations,.... Hibernate has provided an alternative for HQL , that is, "Native SQL". If we want to use Native SQL in Hibernate applications then we have to use the following steps.
- Create SqlQuery object
- Execute the SQL query.
Create SqlQuery object
SqlQuery is an object provided by Hibernate in the form of org.hibernate.SqlQuery interface and it able to represent a native sql query.
To create SqlQuery object we have to use the following method.
public SqlQuery createSqlQuery(String query)throws HibernateException EX: SqlQuery query = session.createSqlQuery("select * from emp1");
Execute the SQL query — Employee.java
To execute Sql Query represent by SqlQuery object we have to use the following methods.
public List list() pubhlic Iterator iterator() public ScrollableResults scroll() public Object uniqueResult() public int executeUpdate()
In Native SQL, there are two types of SQL queries.
- Entity SQL Queries
- Scalar SQL Queries
1) Entity SQL Query
Entity SQLQueries are database dependent sql queries, it can be used to retrive the complete records in the form of an Entity. It will include '*' notation to get all columns data in a record in the form of Entity object.
EX: SqlQuery query = session.createSqlQuery("select * from emp1");
Before executing the query we have to provide entity type to SqlQuery object inorder to store results, for this, we have to use the following method.
public void addEntity(Class cl)
EX: query.addEntity(com.durgasoft.hibernate.Employee.class);
Example:
Execute the SQL query — hibernate.cfg.xml
Execute the SQL query — Test.java
Execute the SQL query
In Native SQL, there are two types of parameters.
- Positional Parameters
- Named Parameters
Positional parameters are represented in the form of '?' s , we are able to provide more than one positional parameter with in a single sql query. To set values to the positional parameters we have to use the following method from SqlQuery.
public void setXXX(int param_Index, XXX value) Where xxx may be byte, short, int,...
Names parameters are represented in the form of ':name' , we are able to provide more than one named parameter in native sql query. To provide values to the named parameters we have to use the following method.
public void setXXX(String param_Name, xxx value) Where xxx may be byte, short, int,....
In a single native sql query, we are able to provide both positional parameters and named parameters, but, fiorst we must provide all positional parameters after that only we have to provide named parameters, we must not provide any positional parameter after named parameter.
Execute the SQL query — Employee.java
In the above approach, we have declare sql query directly in client application, it is available upto the present client application only, it is not available to other client applications, this approach is called as "Programatic Approach".
In Hibernate applications, if we want use the same sql query in more than one client application then programatic approach is nit suggetible, at each and every client application we have to hardcode the query, it is not suggestible, to overcome this problem we have to use "Declarative approach".
In Declarative approach, we will declare native sql query in mapping file along with a particular logical name and we will get that query from mapping file on the basis of the name, this type of sql queries are called as Named SQL Queries.
To declare sql query in mapping file we have to use the following tags in mapping file.
- <hibernate-mapping>
- <sql-query name="--">
- <return class="--">
- ---sql query------
- </sql-query>
- </hibernate-mapping>
'name' attribute in <sql-query> tag will take logical name to the query. <return> tag will take a pojo class name with 'class' attribute inorder to get results in the form of POJO objects.
To get named sql query from mapping file to hibernate Client Application we have to use the following method.
public Query getNamedQuery(String logical_Name) In Declartive native sql query we are able to provide both positional parameters and named parameters depending on the requirement.
Note: In Native SQL queueris we are unable to use '<' symbol in mapping file, because, '<' symbol is treated as starting tag form xml tags, inplace of '<' symbol we have to use '<' symbol in mapping file.
EX:
Execute the SQL query — Employee.hbm.xml
Execute the SQL query — hibernate.cfg.xml
Execute the SQL query — Test.java
Scalar SQL Queries — Employee.java
It is a native SQL query, it able to retrive records data from individual columns and it able to generate results in the form of Object[].
EX: select eno, ename, esal, eaddr from emp1;
To represent scalar sql queries we will use org.hibernate.SqlQuery, to get SqlQuery object we will use the following method.
public SqlQuery createSqlQuery(String query)throws HibernateException
Example:
Scalar SQL Queries — Employee.hbm.xml
Scalar SQL Queries — hibernate.cfg.xml
Scalar SQL Queries — Test.java
Scalar SQL Queries
In Scalar SQL Queries we are able to provide both Positional parameters and Named parameters ,but, first we must provide positional parameters after that only we must provide named parameters. If we provide positional parameters and named parameters in sql query then we must provide values to these parameters , for this, we must use the following methods. public void setXXX(int index, xxx value) public void setXXX(String param_Namem , xxx value)
Scalar SQL Queries — Employee.java
In Hibernate applications, we are able to provide scalar sql queries in diclarative manner in mapping file. To declare scalar sql queries in mapping file we have to use the following syntax.
- <hibernate-mapping>
- <sql-query name="--">
- <return-scalar column="--" type="--"/>
- ------scalar sql query ------
- </sql-query>
- </hibernate-mapping>
where <return-scalar> tag is able to represent a particular scalar[column name], for which, we have to declare data type by using 'type' attribute.
Note: In Named scalar sql query we are able to provide both positional parameters and named parameters, first we have to provide positional parameters after that we have to provide named parameters.
Example:
Scalar SQL Queries — Employee.hbm.xml
Scalar SQL Queries — hibernate.cfg.xml
Scalar SQL Queries — Test.java
- Key ideas of Hibernate - Native SQL Queries explained simply
- Ready-to-use code examples
- Exam-style questions at the end