Archive for July, 2007

228 CHAPTER 11 n FILTERING THE RESULTS OF (Shared web hosting)

Tuesday, July 31st, 2007

228 CHAPTER 11 n FILTERING THE RESULTS OF SEARCHES CHAPTER 11 n FILTERING THE RESULTS OF SEARCHES to map values to parameters. Once you have defined your filter, you need to attach the filter definition to a class. At the end of our User class definition, we specify that it uses a filter named activatedFilter. We then need to set a condition corresponding to an HQL WHERE clause for the attached filter. In our case, we used :activatedParam = activated, where :activatedParam is the named parameter specified on the filter definition, and activated is the column name from the user table. You should ensure that the named parameter goes on the left-hand side so that Hibernate s generated SQL doesn t interfere with any joins. Listing 11-1. Hibernate XML Mapping for User
With the filter definition created and attached to a class with a suitable condition, we need to activate the filter. The next class, SimpleFilterExample, inserts several user records into the database, and then immediately displays them to the screen. The class uses a very simple HQL query (from User) to obtain the result set from Hibernate. The displayUsers() method writes the usernames and activation status out to the console. Before you have enabled any filters on the database, this method will return the full list of users. Once you have enabled the first filter (activatedFilter) to show only activated users, call the same displayUsers() method the results of the query are the same as if you had added a WHERE clause containing an “activated=true” clause. You can just as easily change the filter s parameter value to show inactive users, as shown in Listing 11-2.
We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.

Web hosting - CHAPTER 11 n FILTERING THE RESULTS OF SEARCHES

Tuesday, July 31st, 2007

CHAPTER 11 n FILTERING THE RESULTS OF SEARCHES 227 n FILTERING THE RESULTS OF SEARCHES 227 Using Filters in Your Application Your application programmatically determines which filters to activate or deactivate for a given Hibernate session. Each session can have a different set of filters with different parameter values. By default, sessions do not have any active filters you must explicitly enable filters programmatically for each session. The Sessioninterface contains several methods for working with filters, as follows: public Filter enableFilter(String filterName) public Filter getEnabledFilter(String filterName) public void disableFilter(String filterName) These are pretty self-explanatory the enableFilter(String filterName)method activates the specified filter, the disableFilter(String filterName)method deactivates the method, and if you have already activated a named filter, getEnabledFilter(String filterName)retrieves that filter. The org.hibernate.Filterinterface has six methods. You are unlikely to use validate(); Hibernate uses that method when it processes the filters. The other five methods are as follows: public Filter setParameter(String name, Object value) public Filter setParameterList(String name, Collection values) public Filter setParameterList(String name, Object[] values) public String getName() public FilterDefinition getFilterDefinition() The setParameter()method is the most useful. You can substitute any Java object for the parameter, although its type should match the type you specified for the parameter when you defined the filter. The two setParameterList()methods are useful for using INclauses in your filters. If you want to use BETWEENclauses, use two different filter parameters with different names. Finally, the getFilterDefinition()method allows you to retrieve a FilterDefinitionobject representing the filter metadata (its name, its parameters names, and the parameter types). Once you have enabled a particular filter on the session, you do not have to do anything else to your application to take advantage of filters, as we demonstrate in the following example. A Basic Filtering Example Because filters are very straightforward, a basic example allows us to demonstrate most of the filter functionality, including activating filters and defining filters in mapping documents. In the following Hibernate XML mapping document (User.hbm.xml), we created a filter definition called activatedFilter. The parameters for the filter must be specified with XML elements (as shown in Listing 11-1), which use the XML element. You need to specify a type for the filter parameter so that Hibernate knows how
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

226 CHAPTER (Free web hosts) 11 n FILTERING THE RESULTS OF

Monday, July 30th, 2007

226 CHAPTER 11 n FILTERING THE RESULTS OF SEARCHES CHAPTER 11 n FILTERING THE RESULTS OF SEARCHES filter would specify that the status column must match a named parameter. You would not need to define the possible values of the status column in the Hibernate mapping document the application can specify those parameters at run time. Although it is certainly possible to write applications with Hibernate that do not use filters, we find them to be an excellent solution to certain types of problems notably security and personalization. Defining Filters Your first step is to define filters in your application s Hibernate mapping documents, using the XML element. These filter definitions must contain the name of the filter and the names and types of any filter parameters. Specify filter parameters with the XML element. Filter parameters are similar to named parameters for HQL queries. Both require a :before the parameter name. Here is an excerpt from a mapping document with a filter called latePaymentFilter defined: Once you have created the filter definitions, you need to attach the filters to class or collection mapping elements. You can attach a single filter to more than one class or collection. To do this, you add a XML element to each class and/or collection. The XML element has two attributes: name and condition. The name references a filter definition (for instance: latePaymentFilter). The condition represents a WHERE clause in HQL. Here s an example: Each XML element must correspond to a element. You may have more than one filter for each filter definition, and each class can have more than one filter. This is a little confusing the extra level of abstraction allows you to define all the filter parameters in one place and then refer to them in the individual filter conditions.
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

Filtering the Results of Searches CHAPTER 1 1 (Web host music)

Monday, July 30th, 2007

Filtering the Results of Searches CHAPTER 1 1 n n n Filtering the Results of Searches CHAPTER 1 1 n n n Your application will often need to process only a subset of the data in the database tables. In these cases, you can create a Hibernate filter to eliminate the unwanted data. Filters provide a way for your application to limit the results of a query to data that passes the filter s criteria. Filters are not a new concept you can achieve much the same effect using SQL database views but Hibernate offers a centralized management system for them. Unlike database views, Hibernate filters can be enabled or disabled during a Hibernate session. In addition, Hibernate filters can be parameterized, which is particularly useful when you are building applications on top of Hibernate that use security roles or personalization. When to Use Filters As an example, consider a web application that manages user profiles. Currently, your application presents a list of all users through a single web interface, but you receive a change request from your end user to manage active users and expired users separately. For this example, assume that the status is stored as a column on the user table. One way to solve this problem is to rewrite every HQL SELECTquery in your application, adding a WHEREclause that restricts the result by the user s status. Depending on how you built your application, this could be an easy undertaking or it could be complex, but you still end up modifying code that you have already tested thoroughly, potentially changing it in many different places. With Hibernate 3, you can create a filter restriction for the user status. When your end user selects the user type (active or expired), your application activates the user status filter (with the proper status) for the end user s Hibernate session. Now, any SELECT queries will return the correct subset of results, and the relevant code for the user status is limited to two locations: the Hibernate session and the user status filter. The advantage of using Hibernate filters is that you can programmatically turn filters on or off in your application code, and your filters are defined in your Hibernate mapping documents for easy maintainability. The major disadvantage of filters is that you cannot create new filters at run time. Instead, any filters your application requires need to be specified in the proper Hibernate mapping document. Although this may sound somewhat limiting, the fact that filters can be parameterized makes them pretty flexible. For our user status filter example, only one filter would need to be defined in the mapping document (albeit in two parts). That
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

Web hosting reviews - CHAPTER 10 n ADVANCED QUERIES USING CRITERIA 223

Monday, July 30th, 2007

CHAPTER 10 n ADVANCED QUERIES USING CRITERIA 223 n ADVANCED QUERIES USING CRITERIA 223 Criteria prdCrit = session.createCriteria(Product.class); Product product = new Product(); product.setName(”M%”); Example prdExample = Example.create(product); prdExample.excludeProperty(”price”); prdExample.enableLike(); Criteria suppCrit = prdCrit.createCriteria(”supplier”); Supplier supplier = new Supplier(); supplier.setName(”SuperCorp”); suppCrit.add(Example.create(supplier)); prdCrit.add(prdExample); List results = prdCrit.list(); We also ignore the price property for our product, and we use LIKE for object comparison, instead of equals. The QBE API works best for searches in which you are building the search from user input. The Hibernate team recommends using QBE for advanced searches with multiple fields, because it s easier to set values on business objects than to manipulate restrictions with the Criteria API. Summary Using the Criteria API is an excellent way to get started developing with HQL. The developers of Hibernate have provided a clean API for adding restrictions to queries with Java objects. Although HQL isn t too difficult to learn, some developers prefer the Criteria Query API, as it offers compile-time syntax checking although column names and other schema-dependent information cannot be checked until run time. In the next chapter, we discuss the use of Hibernate filters to restrict the range of data against which queries are applied.
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

222 CHAPTER 10 n ADVANCED QUERIES USING CRITERIA (Web server address)

Sunday, July 29th, 2007

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.

Web site templates - CHAPTER 10 n ADVANCED QUERIES USING CRITERIA 221

Saturday, July 28th, 2007

CHAPTER 10 n ADVANCED QUERIES USING CRITERIA 221 n ADVANCED QUERIES USING CRITERIA 221 create a Projection for a property. When you execute this form of query, the list()method returns a Listof Objectarrays. Each Objectarray contains the projected properties for that row. The following example returns just the contents of the name and description columns from the Productdata. Remember, Hibernate is polymorphic, so this also returns the name and description from the Software objects that inherit from Product. Criteria crit = session.createCriteria(Product.class); ProjectionList projList = Projections.projectionList(); projList.add(Projections.property(”name”)); projList.add(Projections.property(”description”)); crit.setProjection(projList); List results = crit.list(); Use this query style when you want to cut down on network traffic between your application servers and your database servers. For instance, if your table has a large number of columns, this can slim down your results. In other cases, you may have a large set of joins that would return a very wide result set, but you are only interested in a few columns. Lastly, if your clients have limited memory, this can save you trouble with large datasets. But make sure you don t have to retrieve additional columns for the entire result set later, or your optimizations may actually decrease performance. You can group your results (using SQL s GROUP BY clause) with the groupPropertyprojection. The following example groups the products by name and price: Criteria crit = session.createCriteria(Product.class); ProjectionList projList = Projections.projectionList(); projList.add(Projections.groupProperty(”name”)); projList.add(Projections.groupProperty(”price”)); crit.setProjection(projList); List results = crit.list(); As you can see, projections open up aggregates to the Criteria API, which means that developers do not have to drop into HQL for aggregates. Projections offer a way to work with data that is closer to the JDBC result set style, which may be appropriate for some parts of your application. Query By Example (QBE) In this section, because of the confusing terminology, we will refer to excerpts from our demonstration code as samples rather than examples, reserving example for its peculiar technical meaning in the context of QBE. In QBE, instead of programmatically building a Criteria object with Criterion objects and logical expressions, you can partially populate an instance of the object. You use this instance as a template and have Hibernate build the criteria for you based upon its values. This keeps your code clean and makes your project easier to test. The org.hibernate. criterion.Example class contains the QBE functionality. Note that the Example class implements the Criterion interface, so you can use it like any other restriction on a criteria query. For instance, if we have a user database, we can construct an instance of a user object, set the property values for type and creation date, and then use the Criteria API to run a
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

220 CHAPTER 10 n ADVANCED QUERIES (Web site templates) USING CRITERIA

Saturday, July 28th, 2007

220 CHAPTER 10 n ADVANCED QUERIES USING CRITERIA CHAPTER 10 n ADVANCED QUERIES USING CRITERIA To use projections, start by getting the org.hibernate.criterion.Projection object you need from the org.hibernate.criterion.Projections factory class. The Projectionsclass is similar to the Restrictions class in that it provides several static factory methods for obtaining Projection instances. After you get a Projectionobject, add it to your Criteria object with the setProjection()method. When the Criteria object executes, the list contains object references that you can cast to the appropriate type. The row-counting functionality provides a simple example of applying projections. The code looks similar to the restrictions examples we were working with earlier in the chapter: Criteria crit = session.createCriteria(Product.class); crit.setProjection(Projections.rowCount()); List results = crit.list(); The results list will contain one object, an Integer that contains the results of executing the COUNTSQL statement. Other aggregate functions available through the Projections factory class include the following: avg(String propertyName): Gives the average of a property s value count(String propertyName): Counts the number of times a property occurs countDistinct(String propertyName): Counts the number of unique values the property contains max(String propertyName): Calculates the maximum value of the property values min(String propertyName): Calculates the minimum value of the property values sum(String propertyName): Calculates the sum total of the property values We can apply more than one projection to a given Criteria object. To add multiple projections, get a projection list from the projectionList()method on the Projections class. The org.hibernate.criterion.ProjectionList object has an add() method that takes a Projection object. You can pass the projections list to the setProjection() method on the Criteria object because ProjectionList implements the Projection interface. The following example demonstrates some of the aggregate functions, along with the projection list: Criteria crit = session.createCriteria(Product.class); ProjectionList projList = Projections.projectionList(); projList.add(Projections.max(”price”)); projList.add(Projections.min(”price”)); projList.add(Projections.avg(”price”)); projList.add(Projections.countDistinct(”description”)); crit.setProjection(projList); List results = crit.list(); When you execute multiple aggregate projections, you get a List with an Object array as the first element. The Object array contains all of your values, in order. Another use of projections is to retrieve individual properties, rather than entities. For instance, we can retrieve just the name and description from our product table, instead of faulting the classes into memory. Use the property() method on the Projections class to
You want to have a cheap webhost for your apache application, then check apache web hosting services.

CHAPTER 10 n ADVANCED QUERIES USING CRITERIA 219 (Web site translator)

Friday, July 27th, 2007

CHAPTER 10 n ADVANCED QUERIES USING CRITERIA 219 n ADVANCED QUERIES USING CRITERIA 219 Criteria crit = session.createCriteria(Supplier.class); Criteria prdCrit = crit.createCriteria(”products”); prdCrit.add(Restrictions.gt(”price”,new Double(25.0))); List results = crit.list(); Going the other way, we obtain all the products from the supplier MegaInc using many- to-one associations: Criteria crit = session.createCriteria(Product.class); Criteria suppCrit = crit.createCriteria(”supplier”); suppCrit.add(Restrictions.eq(”name”,”MegaInc”)); List results = crit.list(); Although we can use either Criteria object to obtain the results, it makes a difference which criteria we use for ordering the results. In the following example, we are ordering the supplier results by the supplier names: Criteria crit = session.createCriteria(Supplier.class); Criteria prdCrit = crit.createCriteria(”products”); prdCrit.add(Restrictions.gt(”price”,new Double(25.0))); crit.addOrder(Order.desc(”name”)); List results = prdCrit.list(); If we wanted to sort the suppliers by the descending price of their products, we would use the following line of code. This code would have to replace the previous addOrder() call on the supplier Criteria object. prdCrit.addOrder(Order.desc(”price”)); Although the products are not in the result set, SQL still allows you to order by those results. If you get mixed up with which Criteriaobject you are using and pass the wrong property name for the sort-by order, Hibernate will throw an exception. Distinct Results If you would like to work with distinct results from a criteria query, Hibernate provides a result transformer for distinct entities, org.hibernate.transform. DistinctRootEntityResultTransformer, which ensures that no duplicates will be in your query s result set. Rather than using SELECT DISTINCT with SQL, the distinct result transformer compares each of your results using their default hashCode() methods, and only adds those results with unique hash codes to your result set. This may or may not be the result you would expect from an otherwise equivalent SQL DISTINCT query, so be careful with this. An additional performance note: the comparison is done in Hibernate s Java code, not at the database, so non-unique results will still be transported across the network. Projections and Aggregates Instead of working with objects from the result set, you can treat the results from the result set as a set of rows and columns. This is similar to how you would use data from a SELECT query with JDBC; also, Hibernate supports properties, aggregate functions, and the GROUP BY clause.
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

218 CHAPTER (Web server application) 10 n ADVANCED QUERIES USING CRITERIA

Friday, July 27th, 2007

218 CHAPTER 10 n ADVANCED QUERIES USING CRITERIA CHAPTER 10 n ADVANCED QUERIES USING CRITERIA Criteria crit = session.createCriteria(Product.class); Criterion price = Restrictions.gt(”price”,new Double(25.0)); crit.setMaxResults(1); Product product = (Product) crit.uniqueResult(); Again, we stress that you need to make sure that your query only returns one or zero results if you use the uniqueResult() method. Otherwise, Hibernate will throw a NonUniqueResultException exception, which may not be what you would expect Hibernate does not just pick the first result and return it. Sorting the Query s Results Sorting the query s results works much the same way with criteria as it would with HQL or SQL. The Criteria API provides the org.hibernate.criterion.Order class to sort your result set in either ascending or descending order, according to one of your object s properties. Create an Order object with either of the two static factory methods on the Order class: asc() for ascending or desc() for descending. Both methods take the name of the property as their only argument. After you create an Order, use the addOrder() method on the Criteria object to add it to the query. This example demonstrates how you would use the Order class: Criteria crit = session.createCriteria(Product.class); crit.add(Restrictions.gt(”price”,new Double(25.0))); crit.addOrder(Order.desc(”price”)); List results = crit.list(); You may add more than one Order object to the Criteria object. Hibernate will pass them through to the underlying SQL query. Your results will be sorted by the first order, then any identical matches within the first sort will be sorted by the second order, and so on. Beneath the covers, Hibernate passes this on to an SQL ORDER BY clause after substituting the proper database column name for the property. Associations To add a restriction on a class that is associated with your criteria s class, you will need to create another Criteria object. Pass the property name of the associated class to the createCriteria() method, and you will have another Criteria object. You can get the results from either Criteria object, although you should pick one style and be consistent for readability s sake. We find that getting the results from the top-level Criteria object (the one that takes a class as a parameter) makes it clear what type of object is expected in the results. The association works going from one-to-many as well as from many-to-one. First, we will demonstrate how to use one-to-many associations to obtain suppliers who sell products with a price over $25. Notice that we create a new Criteriaobject for the products property, add restrictions to the products criteria we just created, and then obtain the results from the supplier Criteria object:
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.