222 CHAPTER 10 n ADVANCED QUERIES USING CRITERIA (Web server address)
222 CHAPTER 10 n ADVANCED QUERIES USING CRITERIA CHAPTER 10 n ADVANCED QUERIES USING CRITERIA QBE query. Hibernate will return a result set containing all user objects that match the property values that were set. Behind the scenes, Hibernate inspects the Exampleobject and constructs an SQL fragment that corresponds to the properties on the Example object. To use QBE, we need to construct an Example object first. Then we need to create an instance of the Exampleobject, using the static create() method on the Example class. The create() method takes the Example object as its argument. You add the Example object to a Criteria object just like any other Criterion object. The following basic example searches for suppliers that match the name on the example Supplier object: Criteria crit = session.createCriteria(Supplier.class); Supplier supplier = new Supplier(); supplier.setName(”MegaInc”); crit.add(Example.create(supplier)); List results = crit.list(); When Hibernate translates our Example object into an SQL query, all the properties on our Example objects get examined. We can tell Hibernate which properties to ignore; the default is to ignore null-valued properties. To search our products or software in the sample database with QBE, we need to either specify a price or tell Hibernate to ignore properties with a value of zero, because we used a double primitive for storage instead of a Double object. The double primitive initializes to zero, while a Double would have been null; and so, left to its own devices, the QBE logic will assume that we are specifically searching for prices of zero, whereas we want it to ignore this default value. We can make the Hibernate Example object exclude zero-valued properties with the excludeZeroes() method. We can exclude properties by name with the excludeProperty() method, or exclude nothing (compare for null values and zeroes exactly as they appear in the Example object) with the excludeNone() method. This sample applies the excludeZeroes() method to ignore the default zero prices: Criteria crit = session.createCriteria(Product.class); Product exampleProduct = new Product(); exampleProduct.setName(”Mouse”); Example example = Example.create(exampleProduct); example.excludeZeroes(); crit.add(example); List results = crit.list(); Other options on the Example object include ignoring the case for strings with the ignoreCase() method, and enabling use of SQL s LIKE for comparing strings, instead of just using equals(). We can also use associations for QBE. In the following sample, we create two examples: one for the product and one for the supplier. We use the technique explained in the Associations section of this chapter to retrieve objects that match both criteria.
From our experience, we can recommend PHP Web Hosting services, if you need affordable webhost to host and run your web application.