Java Reference
In-Depth Information
//See the results of the update
query = session.createQuery("from Supplier");
List results = query.list();
After carrying out this query, any supplier previously named SuperCorp will be named
MegaCorp. You may use a where clause with updates to control which rows get updated, or you
may leave it off to update all rows. Notice that we printed out the number of rows affected by
the query. We also used named parameters in our HQL for this bulk update.
Bulk deletes work in a similar way. Use the delete from clause with the class name you
would like to delete from. Then use the where clause to narrow down which entries in the table
you would like to delete. Use the executeUpdate() method to execute deletes against the data-
base as well. Our code surrounding the HQL DELETE statement is basically the same—we use
named parameters, and we print out the number of rows affected by the delete:
String hql = "delete from Product where name = :name";
Query query = session.createQuery(hql);
query.setString("name","Mouse");
int rowCount = query.executeUpdate();
System.out.println("Rows affected: " + rowCount);
//See the results of the update
query = session.createQuery("from Product");
List results = query.list();
n Caution Using bulk updates and deletes in HQL works almost the same as in SQL, so keep in mind that
these are powerful and can erase the data in your tables if you make a mistake with the where clause.
Named Queries for HQL and SQL
One of Hibernate's best features is the named query, in which your application can store its
HQL queries outside the application in the mapping file. This has many benefits for applica-
tion maintenance. The first benefit is that many objects can share queries—you could set up
static final strings on classes with the HQL queries, but Hibernate already provides a nice
facility for the same thing. The next benefit is that named queries could also contain native
SQL queries—the application calling the named query does not need to know if the named
query is SQL or HQL. This has enormous benefits for migrating SQL-based applications to
Hibernate. The last benefit is that you can provide your HQL and SQL queries in a configura-
tion file to your database administrators, who will probably find it easier to work with an
XML mapping file than with HQL statements embedded in Java code.
Add named queries in the appropriate Hibernate mapping file. HQL queries use the XML
<query> element, and SQL queries use the XML <sql-query> element. Both of these XML ele-
ments require a name attribute that uniquely identifies the query in the application. With one
Search WWH ::




Custom Search