Native SQL Queries
In addition to HQL and Criteria, Hibernate allows you to retrieve data from the database using native SQL. Describing SQL would go beyond the scope of this text, but it should be noted here that Hibernate requires aliases to be used when working with native SQL. The aliases are used to bind the SQL to the returned objects. Listing 8.7 shows an example of the execution of a native SQL statement binding to the return objects.
Listing 8.7. Executing Native SQL
session.createSQLQuery("SELECT {student.*} FROM student AS {student}
WHERE ID<10", "student", Student.class).list();
If you simply wish to execute raw SQL against the database (and not retrieve a set of objects bound to a query), you will probably need to query the session for the underlying JDBC connection. An example of the use of raw SQL execution from a Hibernate session can be found in Listing 2.7 (the setInnoDB() method).
Keep in mind that SQL statements mixed with other statements may not execute in the order desired unless you use the Session.flush() method. For more on this, see Chapter 9.
The full scope and theory of SQL is beyond the scope of this book (especially considering the wide variety of proprietary extensions). Consult your database documentation or another text on SQL for more information on native SQL queries.
|