Hibernate Native sql query with example

  • By Using Hibernate Native SQL we can write database dependent queries as part of hibernate.
  • Hibernate Native Sql allows us to write create , update,  delete and insert queries.
  • We can also call Stored procedures using Hibernate Native Sql.
  • When the query is too complex using HQL then we need to use hibernate sql query.
  • Hibernate uses the org.hibernate.SQLQuery interface for native SQL
    1. SQLQuery is a sub interface of Query
    2. Use createSQLQuery() factory method on Session to create SQLQuery object.
  •  Hibernate SQLQuery must be associated with an existing Hibernate entity or scalar result.



Hibernate native sql insert query example

  1. Session session = sessionFactory.openSession();
  2. session.beginTransaction();
  3.  
  4. SQLQuery insertsqlQuery = session.createSQLQuery("INSERT INTO
  5. Physician(firstname,lastname,fee,hospital)VALUES(?,?,?,?)");
  6.  
  7.  insertsqlQuery.setParameter(0, "Saidesh");
  8.  insertsqlQuery.setParameter(1, "Kilaru");
  9.  insertsqlQuery.setParameter(2, 50); 
  10.  insertsqlQuery.setParameter(3, "Yashoda");        
  11.  insertsqlQuery.executeUpdate();

 Hibernate scalar query example

  • Writing a Hibernate Sql query to get list of  scalars or values from single or multiple tables.
  • Lets see an example on Hibernate scalar query.


  1. String hibernate_sql = "SELECT first_name, fee FROM  Physician";
  2. SQLQuery query = session.createSQLQuery(hibernate_sql);
  3. query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
  4. List results = query.list();

 Hibernate named sql Queries

  • Writing a Hibernate Sql query to get entity object by using addEntity() method.
  • Lets see an example on Hibernate named sql query

hibernate native sql query parameters scalar


Hibernate Named Query Introduction Tutorial

  • If we are using HQL or Native SQL queries multiple time then it will be code mess because all queries will be scattered throughout the project.
  • Hibernate Named Query is a way to use queries by giving a name.
  • Hibernate Named Queries will be defined at one place and used anywhere in the project.
  • use of named query in hibernate
  • Writing HQL query in HBM file is called HQL Named Query.
  • Or we can use @NameQuery annotation in entity.
  • For writing Hibernate Named Queries we will use <query> tag in Hibernate mapping file Or @NameQuery annotation in the entity.
  • If we want to create Named Query using hibernate mapping file then we need to use query element.



Advantages of Named Query in Hibernate 

  • Global access
  • Easy to maintain.

Hibernate Named Queries by using Annotations:

  • If we want to create Named Queries using annotations in entity class then we need to use @NameQueries and @NameQuery annotations
  • @NameQuery will be used to create single Query
  • @NameQueries annotations will be used to create multiple Queries. When we are using @NameQueries for every query we need to use @NameQuery annotation.

Hibernate Named Query example by using Annotations:


Hibernate Named Query example join

  1. Query query = session.getNamedQuery("findDocterById");
  2.         query.setInteger("id", 37);
  3.        List empList = query.list();


Hibernate Named Queries by using Hibernate mapping file:

  • We need to configure Hibernate Named Queries as part of Hibernate mapping file.
  • By using <query> element we need to write Hibernate named Queries.

  1. <hibernate_mapping>
  2.             <class  >
  3.             ---------
  4.             </class>
  5.  
  6.  <query name = “findDocterById”>
  7.  <![CDATA[from Docter s where s.id = :id]]>
  8. </query>  

  9.  </hibernate_mapping>     


  1. Query query = session.getNamedQuery("findDocterById");
  2.         query.setInteger("id", 64);
  3.        List empList = query.list();

Hibernate Criteria Query Language (HCQL)

  • In Hibernate we pull the data from data base in two ways.
  • session.get()/ session.load()
  • Hibernate query langugae
  • Now we will discuss about the third way Hibernate criteria query language which solves the problems of above two approaches.




Hibernate Criteria Query Language / HCQL

  • In order to fetch the records based on some criteria we use Hibernate Criteria Query Language.
  • We can make select operation on tables by applying some conditions by using HCQL.
  • Criteria API is the alternative to HQL in object oriented approach.  
  • We can execute only SELECT statements using Criteria; we can’t execute UPDATE, DELETE statements using Criteria.

Advantages of  Hibernate Criteria Query Language (HCQL) 

  • Criteria API allows us to define criteria query object by applying rules ,filtration and logical conditions
  • So that we can add criteria to query.
  • Criteria is also database independent, Because it internally generates HQL queries.
  • Criteria is suitable for executing dynamic queries
  • Criteria API also include Query by Example (QBE) functionality for supplying example objects.
  • Criteria also includes projection and aggregation methods
     

Criteria Interface:

  • Criteria Interface has some methods to specify criteria.
  • Hibernate session interface has a method named createCriteria() to create criteria.

  1. public interface Criteria  extends CriteriaSpecification

  1. Criteria criteria = session.createCriteria(Student.class);
  2. List<Student> studentList= criteria .list();

Methods of Criteria interface:

  
Hibernate add crieria example hcql


Order Class

  1. public class Order extends Object implements Serializable
 
  • By using Order class we can sort the records in ascending or descending order.
  • Order class provides two different methods to make ascending and descending.
  1. public static Order asc(String propertyName)
  2. public static Order desc(String propertyName)

Hibernate Criteria query example using order class

  1.  Criteria criteria = session.createCriteria(Product.class)
  2.  
  3. // To sort records in descening order
  4. criteria.addOrder(Order.desc("price"));
  5.  
  6. // To sort records in ascending order
  7. criteria.addOrder(Order.asc("price"));

Restrictions Class

  1. public class Restrictions extends Object

  • Restrictions class provides methods that can be used  add restrictions (conditions) to criteria object.
  • We have many methods in Restrictions class some of the commonly using methods are.

hibernate criteria add example interview questions


Hibernate Criteria query example using Restrictions class


  1.  Criteria criteria = session.criteriaeateCriteria(Product.class);
  2. // To get records having price more than 3000
  3. criteria.add(Restrictions.gt("price", 3000));
  4.  
  5. // To get records having price less than 2000
  6. criteria.add(Restrictions.lt("price", 2000));
  7.  
  8. // To get records having productName starting with criteriaite
  9. criteria.add(Restrictions.like("productName", "criteriaite%"));
  10.  
  11. // Case sensitive form of the above restriction.
  12. criteria.add(Restrictions.ilike("productName", "zara%"));
  13.  
  14. // To get records having price in between 1000 and 2000
  15. criteria.add(Restrictions.between("price", 1000, 2000));
  16.  
  17. // To check if the given property price is null
  18. criteria.add(Restrictions.isNull("price"));
  19.  
  20. // To check if the given property is not null
  21. criteria.add(Restrictions.isNotNull("price"));
  22.  
  23. // To check if the given property price is empty
  24. criteria.add(Restrictions.isEmpty("price"));
  25.  
  26. // To check if the given property price is not empty
  27. criteria.add(Restrictions.isNotEmpty("price"));
  28.  
  29. List results = criteria.list();

Pagination using Hibernate Criteria

  • By using criteria methods setFirstResult() and setMaxResults() we can achieve pagination concept.


  1. Criteria criteria = session.createCriteria(Product.class);
  2. criteria.setMaxResults(10);
  3. criteria.setFirstResult(20);

Projections class in Hibernate

  1. public final class Projections extends Object

  • By Using org.hibernate.criterion.Projections  class methods we can perform operations like minimum , maximum, average , sum and count.

Hibernate Criteria query example using Projection class

  1. Criteria criteria = session.criteriaeateCriteria(Product.class);
  2.  
  3. // To get total row count.
  4. criteria.setProjection(Projections.rowCount());
  5.  
  6. // To get average price.
  7. criteria.setProjection(Projections.avg("price"));
  8.  
  9. // To get distinct countof name
  10. criteria.setProjection(Projections.countDistinct("name"));
  11.  
  12. // To get maximum price
  13. criteria.setProjection(Projections.max("price"));
  14.  
  15. // To get minimum price
  16. criteria.setProjection(Projections.min("price"));
  17.  
  18. // To get sum of price
  19. criteria.setProjection(Projections.sum("price"))

Advantages and disadvantages of hibernate compared to jdbc

Advantages of Hibernate over JDBC:

  1. Hibernate is an ORM tool
  2. Hibernate is an open source framework.
  3. Better than JBDC.
  4. Hibernate has an exception translator , which converts checked exceptions of JDBC in to unchecked exceptions of hibernate. So all exceptions in hibernate are unchecked exceptions and Because of this no need to handle exceptions explicitly.
  5. Hibernate supports inheritance and polymorphism.
  6. With hibernate we can manage the data stored across multiple tables, by applying relations(association)
  7. Hibernate has its own query language called Hibernate Query Language. With this HQL hibernate became database independent.
  8. Hibernate supports relationships like One-To-One, One-To-Many, Many-To-One ,Many-To-Many.
  9. Hibernate has Caching mechanism. using this number of database hits will be reduced. so performance of an application will be increases.
  10. Hibernate supports lot of databases.
  11. Hibernate supported databases List.
  12. Hibernate is a light weight framework because hibernate uses POJO classes for data transfer between application and database.
  13. Hibernate has versioning and time stamp feature with this we can know how many number of times data is modified.
  14. Hibernate also supports annotations along with XML.
  15. Hibernate supports Lazy loading.
  16. Hibernate is easy to learn it is developers friendly.
  17. The architecture is layered to keep you isolated from having to know the underlying APIs.
  18. Hibernate maintains database connection pool.
  19. Hibernate  has Concurrency support.
  20. Using Hibernate its Easy to maintain and it will increases productivity


Disadvantages of Hibernate Compared to JDBC!!:
  • Hibernate is slow compared to JDBC because of generating many sql queries at run time but this is not considered as dis advantage in my view.
  • Below are some of the dis advantages but these are not applicable to small applications. But we have given some possible scenarios. 

advantages and disadvantages of hibernate

Hibernate supported databases List

  • Hibernate is an ope source framework and also called as an ORM tool.
  • Hibernate supports lot of databases. 
  • Please find below list of databases that are supported by hibernate.
  • Hibernate supported databases list 


  1. DB2    
  2. DB2 AS/400   
  3. DB2 OS390 
  4. FrontBase
  5. Firebird  
  6. HypersonicSQL 
  7. H2 Database  
  8. Informix   
  9. Ingres  
  10. Interbase
  11. MySQL5    
  12. MySQL5 with InnoDB    
  13. MySQL with MyISAM    
  14. Mckoi SQL
  15. Microsoft SQL Server 2000    
  16. Microsoft SQL Server 2005  
  17. Microsoft SQL Server 2008  
  18. Oracle
  19. Oracle 9i   
  20. Oracle 10g    
  21. Oracle 11g      
  22. PostgreSQL  
  23. Progress   
  24. Pointbase
  25. SAP DB
  26. Sybase
  27. Sybase 

  •  Following is the list of various important databases dialects for corresponding database.

hibernate supported databases
Select Menu