Click here to download eclipse supported ZIP file
We looked into Hibernate Query Language and Hibernate Criteria in recent posts, today we will look into Hibernate Native SQL query with examples.
Hibernate provide option to execute native SQL queries through the use of SQLQuery object. This is very handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.
For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first level caching.
I will use MySQL database and same tables and data setup as used in HQL example, so you should check out that first to understand the tables and corresponding model classes mapping.
You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3.x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.
Your application will create a native SQL query from the session with the createSQLQuery() method on the Session interface.:
public SQLQuery createSQLQuery(String sqlString) throws HibernateException
After you pass a string containing the SQL query to the createSQLQuery() method, you can associate the SQL result with either an existing Hibernate entity, a join, or a scalar result using addEntity(), addJoin(), and addScalar() methods respectively.
Named SQL queries:
The following is the syntax to get entity objects from a native sql query via addEntity() and using named SQL query.
String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id"; SQLQuery query = session.createSQLQuery(sql); query.addEntity(EmployeeBean.class); query.setParameter("employee_id", 10); List results = query.list();Using a
SQLQuery
No comments:
Post a Comment