Michigan web site - 208 CHAPTER 9 n SEARCHES AND QUERIES CHAPTER
208 CHAPTER 9 n SEARCHES AND QUERIES CHAPTER 9 n SEARCHES AND QUERIES //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 whereclause 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 database 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(); nCaution 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 application 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 configuration 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
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.