CHAPTER 15 Advanced query options The second way
CHAPTER 15 Advanced query options The second way to express inner joins with the Criteria API is to assign an alias to the joined entity: session.createCriteria(Item.class) .createAlias(”bids”, “b”) .add( Restrictions.like(”description”, “%Foo%”) ) .add( Restrictions.gt(”b.amount”, new BigDecimal(99) ) ); And the same for a restriction on a single-valued association, the seller: session.createCriteria(Item.class) .createAlias(”seller”, “s”) .add( Restrictions.like(”s.email”, “%hibernate.org” ) ); This approach doesn t use a second instance of Criteria; it s basically the same alias assignment mechanism you d write in the FROM clause of an HQL/JPA QL statement. Properties of the joined entity must then be qualified by the alias assigned in createAlias() method, such as s.email. Properties of the root entity of the criteria query (Item) may be referred to without the qualifying alias, or with the alias “this”: session.createCriteria(Item.class) .createAlias(”bids”, “b”) .add( Restrictions.like(”this.description”, “%Foo%”) ) .add( Restrictions.gt(”b.amount”, new BigDecimal(99) ) ); Finally, note that at the time of writing only joining of associated entities or collections that contain references to entities (one-to-many and many-to-many) is supported in Hibernate with the Criteria API. The following example tries to join a collection of components: session.createCriteria(Item.class) .createAlias(”images”, “img”) .add( Restrictions.gt(”img.sizeX”, 320 ) ); Hibernate fails with an exception and tells you that the property you want to alias doesn t represent an entity association. We think this feature will likely be implemented by the time you read this book. Another syntax that is also invalid, but that you may be tempted to try, is an implicit join of a single-valued association with the dot notation: session.createCriteria(Item.class) .add( Restrictions.like(”seller.email”, “%hibernate.org”) ); The “seller.email” string isn t a property or a component s property path. Create an alias or a nested Criteria object to join this entity association. Let s discuss dynamic fetching of associated objects and collections.
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.