CHAPTER 15 Advanced query options As a consequence, (Hosting your own web site)
CHAPTER 15 Advanced query options As a consequence, criteria queries may return duplicate references to distinct instances of the root entity, even if you don t apply FetchMode.JOIN for a collection in your query. The last query example may return hundreds of Item references, even if you have only a dozen in the database. Remember our discussion in Dynamic fetching strategies with joins, in chapter 14, section 14.3.1 and look again at the SQL statement and resultset in figure 14.3. You can remove the duplicate references in the result List by wrapping it in a LinkedHashSet (a regular HashSet wouldn t keep the order or the query result). In HQL and JPA QL, you can also use the DISTINCT keyword; however, there is no direct equivalent of this in Criteria. This is where the ResultTransformer becomes useful. Applying a result transformer A result transformer can be applied to a query result so that you can filter or marshal the result with your own procedure instead of the Hibernate default behavior. Hibernate s default behavior is a set of default transformers that you can replace and/or customize. All criteria queries return only instances of the root entity, by default: List result = session.createCriteria(Item.class) .setFetchMode(”bids”, FetchMode.JOIN) .setResultTransformer(Criteria.ROOT_ENTITY) .list(); Set distinctResult = new LinkedHashSet(result); The Criteria.ROOT_ENTITY is the default implementation of the org.hibernate.transform.ResultTransformer interface. The previous query produces the same result, with or without this transformer set. It returns all Item instances and initializes their bids collections. The List probably (depending on the number of Bids for each Item) contains duplicate Item references. Alternatively, you can apply a different transformer: List distinctResult = session.createCriteria(Item.class) .setFetchMode(”bids”, FetchMode.JOIN) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) .list(); Hibernate now filters out duplicate root entity references before returning the result this is effectively the same filtering that occurs in HQL or JPA QL if you use the DISTINCT keyword.
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.