CHAPTER 14 Querying with HQL and JPA QL
CHAPTER 14 Querying with HQL and JPA QL listed in the SELECT clause, Hibernate returns the query results as tuples each row of the query result list is an instance of Object[]. Utilizing dynamic instantiation Tuples, especially common with report queries, are inconvenient, so HQL and JPA QL provide a SELECT NEW constructor call. In addition to creating new objects dynamically with this technique, you can also use it in combination with aggregation and grouping. If you define a class called ItemBidSummary with a constructor that takes a Long, a Long, and a BigDecimal, the following query may be used: select new ItemBidSummary( bid.item.id, count(bid), avg(bid.amount) ) from Bid bid where bid.item.successfulBid is null group by bid.item.id In the result of this query, each element is an instance of ItemBidSummary, which is a summary of an Item, the number of bids for that item, and the average bid amount. Note that you have to write a fully qualified classname here, with a package name. unless the class has been imported into the HQL namespace (see chapter 4, section 4.3.3, “Naming entities for querying”). This approach is type-safe, and a data transfer class such as ItemBidSummary can easily be extended for special formatted printing of values in reports. The ItemBidSummary class is a Java bean, it doesn t have to be a mapped persistent entity class. On the other hand, if you use the SELECT NEW technique with a mapped entity class, all instances returned by your query are in transient state so you can use this feature to populate several new objects and then save them. Report queries can have an impact on the performance of your application. Let s explore this issue some more. Improving performance with report queries The only time we have ever seen any significant overhead in Hibernate code compared to direct JDBC queries and then only for unrealistically simple toy test cases is in the special case of read-only queries against a local database. In this case, it s possible for a database to completely cache query results in memory and respond quickly, so benchmarks are generally useless if the dataset is small: Plain SQL and JDBC are always the fastest option. Hibernate, on the other hand, even with a small dataset, must still do the work of adding the resulting objects of a query to the persistence context cache
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.