In this section, you will learn Hibernate Native SQL query.
Using HQL or criteria query in Hibernate, you can execute nearly any type of SQL query. Even so some developer complaint about slowness of statement generated by Hibernate and they opt to generate their own SQL statement. These developer generated query is known as Hibernate Native SQL Query.
You can create native SQL query using Session as follows :
String sql = "SELECT ........."; Query query = session.createSQLQuery(sql);
Using EntityManager , you can create native SQL query as follows:
String sql = "SELECT ........."; Query q = entityManager.createNativeQuery(sql);
Hibernate Native SQL query can be broadly categorized into following types :
This is the most basic SQL query. In this query, we fetch list of scalars or values from one or more database tables. Given below a simple example of Native Scalar query :
String sql = "SELECT enrollemnet,name FROM STUDENT"; Query query = session.createSQLQuery(sql); query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); List results = query.list();
In this type of query, we fetch all the columns of selected row / rows. Through addEntity( ) method selected data will map automatically to the passed class to the addEntity( ) method. Given below example of a simple Entity query:
String sql = "SELECT * FROM STUDENT"; Query query = session.createSQLQuery(sql); query.addEntity(Student.class); List results = query.list();
In this type of query, we fetch all the columns of selected rows but the WHERE conditional values are passed through named variables as follows :
String sql = "SELECT * FROM STUDENT WHERE id = :enrollment_no";
Query query = session.createSQLQuery(sql);
query.addEntity(Student.class);
query.setParameter("enrollment_no", 321123);
List results = query.list();
The main disadvantage of native SQL is - it makes the application database dependent.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Hibernate Native SQL Query Introduction
Post your Comment