Archive for May, 2008

Querying with criteria and (Make web site) example The Criteria API

Saturday, May 31st, 2008

Querying with criteria and example The Criteria API and the org.hibernate.criterion package offer many other operators besides eq() you can use to construct more complex expressions. Creating comparison expressions All regular SQL (and HQL, JPA QL) comparison operators are also available via the Restrictions class: Criterion restriction = Restrictions.between(”amount”, new BigDecimal(100), new BigDecimal(200) ); session.createCriteria(Bid.class).add(restriction); session.createCriteria(Bid.class) .add( Restrictions.gt(”amount”, new BigDecimal(100) ) ); String[] emails = { “foo@hibernate.org”, “bar@hibernate.org” }; session.createCriteria(User.class) .add( Restrictions.in(”email”, emails) ); A ternary logic operator is also available; this query returns all users with no email address: session.createCriteria(User.class) .add( Restrictions.isNull(”email”) ); You also need to be able to find users who do have an email address: session.createCriteria(User.class) .add( Restrictions.isNotNull(”email”) ); You can also test a collection with isEmpty(), isNotEmpty(), or its actual size: session.createCriteria(Item.class) .add( Restrictions.isEmpty(”bids”)); session.createCriteria(Item.class) .add( Restrictions.sizeGt(”bids”, 3)); Or you can compare two properties: session.createCriteria(User.class) .add( Restrictions.eqProperty(”firstname”, “username”) ); The criteria query interfaces also have special support for string matching. String matching For criteria queries, wildcarded searches may use either the same wildcard symbols as HQL and JPA QL (percentage sign and underscore) or specify a MatchMode. The MatchMode is a convenient way to express a substring match without string manipulation. These two queries are equivalent:
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.

Simple web server - CHAPTER 15 Advanced query options Criterion emailEq =

Friday, May 30th, 2008

CHAPTER 15 Advanced query options Criterion emailEq = Restrictions.eq(”email”, “foo@hibernate.org”); Criteria crit = session.createCriteria(User.class); crit.add(emailEq); User user = (User) crit.uniqueResult(); You create a Criterion that represents the restriction for an equality comparison and add it to the Criteria. This eq() method has two arguments: first the name of the property, and then the value that should be compared. The property name is always given as a string; keep in mind that this name may change during a refactoring of your domain model and that you must update any predefined criteria queries manually. Also note that the criteria interfaces don t support explicit parameter binding, because it s not needed. In the previous example you bound the string “foo@hibernate.org” to the query; you can bind any java. lang.Object and let Hibernate figure out what to do with it. The unique- Result() method executes the query and returns exactly one object as a result you have to cast it correctly. Usually, you write this a bit less verbosely, using method chaining: User user = (User) session.createCriteria(User.class) .add(Restrictions.eq(”email”, “foo@hibernate.org”)) .uniqueResult(); Obviously, criteria queries are more difficult to read if they get more complex a good reason to prefer them for dynamic and programmatic query generation, but to use externalized HQL and JPA QL for predefined queries. A new feature of JDK 5.0 is static imports; it helps making criteria queries more readable. For example, by adding import static org.hibernate.criterion.Restrictions.*; you re able to abbreviate the criteria query restriction code to User user = (User) session.createCriteria(User.class) .add( eq(”email”, “foo@hibernate.org”) ) .uniqueResult(); An alternative to obtaining a Criterion is a Property object this will be more useful later in this section when we discuss projection: session.createCriteria(User.class) .add( Property.forName(”email”).eq(”foo@hibernate.org”) ); You can also name a property of a component with the usual dot notation: session.createCriteria(User.class) .add( Restrictions.eq(”homeAddress.street”, “Foo”));
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

Querying with criteria and example to work with (Web file server)

Thursday, May 29th, 2008

Querying with criteria and example to work with these APIs, and how to express selection, restriction, joins, and projection. We assume that you ve read the previous chapter and that you know how these operations are translated into SQL. Even if you decide to use the Criteria and Example APIs as your primary way to write queries, keep in mind that HQL and JPA QL are always more flexible due to their string-based nature. Let s start with some basic selection and restriction examples. 15.1.1 Basic criteria queries The simplest criteria query looks like this: session.createCriteria(Item.class); It retrieves all persistent instances of the Itemclass. This is also called the root entity of the criteria query. Criteria queries also support polymorphism: session.createCriteria(BillingDetails.class); This query returns instances of BillingDetails and its subclasses. Likewise, the following criteria query returns all persistent objects: session.createCriteria(java.lang.Object.class); The Criteria interface also supports ordering of results with the addOrder() method and the Order criterion: session.createCriteria(User.class) .addOrder( Order.asc(”lastname”) ) .addOrder( Order.asc(”firstname”) ); You don t need to have an open Session to create a criteria object; a Detached- Criteria can be instantiated and later attached to a Session for execution (or to another Criteria as a subquery): DetachedCriteria crit = DetachedCriteria.forClass(User.class) .addOrder( Order.asc(”lastname”) ) .addOrder( Order.asc(”firstname”) ); List result = crit.getExecutableCriteria(session).list(); Usually you want to restrict the result and don t retrieve all instances of a class. Applying restrictions For a criteria query, you must construct a Criterion object to express a constraint. The Restrictions class provides factory methods for built-in Criterion types. Let s search for User objects with a particular email address:
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

CHAPTER 15 Advanced query options This chapter explains

Thursday, May 29th, 2008

CHAPTER 15 Advanced query options This chapter explains all query options that you may consider optional or advanced. You ll need the first subject of this chapter, the Criteria query interface, whenever you create more complex queries programmatically. This API is much more convenient and elegant than programmatic generation of query strings for HQL and JPA QL. Unfortunately, it s also only available as a native Hibernate API; Java Persistence doesn t (yet) standardize a programmatic query interface. Both Hibernate and Java Persistence support queries written in native SQL. You can embed SQL and stored procedure calls in your Java source code or externalize them to mapping metadata. Hibernate can execute your SQL and convert the resultset into more convenient objects, depending on your mapping. Filtering of collections is a simple convenience feature of Hibernate you won t use it often. It helps you to replace a more elaborate query with a simple API call and a query fragment, for example, if you want to obtain a subset of the objects in a collection. Finally, we ll discuss the optional query result cache we ve already mentioned that it s not useful in all situations, so we ll take a closer look at the benefits of caching results of a query and when you d ideally enable this feature. Let s start with query by criteria and query by example. 15.1 Querying with criteria and example The Criteria and Example APIs are available in Hibernate only; Java Persistence doesn t standardize these interfaces. As mentioned earlier, it seems likely that other vendors, not only Hibernate, support a similar extension interface and that a future version of the standard will include this functionality. Querying with programmatically generated criteria and example objects is often the preferred solution when queries get more complex. This is especially true if you have to create a query at runtime. Imagine that you have to implement a search mask in your application, with many check boxes, input fields, and switches the user can enable. You must create a database query from the user s selection. The traditional way to do this is to create a query string through concatenation, or maybe to write a query builder that can construct the SQL query string for you. You d run into the same problem if you d try to use HQL or JPA QL in this scenario. The Criteria and Example interfaces allow you to build queries programmatically by creating and combining objects in the right order. We now show you how
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Advanced query options This chapter covers Querying (Web site layout)

Wednesday, May 28th, 2008

Advanced query options This chapter covers Querying with Criteria and Example APIs Embedding native SQL queries Collection filters The optional query result cache 663
Check Tomcat Web Hosting services for best quality webspace to host your web application.

CHAPTER 14 (Web host forum) Querying with HQL and JPA QL

Tuesday, May 27th, 2008

CHAPTER 14 Querying with HQL and JPA QL Subqueries are an advanced technique; you should question frequent use of subqueries because queries with subqueries can often be rewritten using only joins and aggregation. However, they re powerful and useful from time to time. 14.4 Summary You re now able to write a wide variety of queries in HQL and JPA QL. You learned in this chapter how to prepare and execute queries, and how to bind parameters. We ve shown you restriction, projection, joins, subselects, and many other options that you probably already know from SQL. Table 14.4 shows a summary you can use to compare native Hibernate features and Java Persistence. Table 14.4 Hibernate and JPA comparison chart for chapter 14 Hibernate Core Java Persistence and EJB 3.0 Hibernate APIs support query execution with listing, iteration, and scrolling. Java Persistence standardizes query execution with listing. Hibernate supports named and positional query bind parameters. Java Persistence standardizes named and positional bind parameter options. Hibernate query APIs support application-level query hints. Java Persistence allows developers to supply arbitrary vendor-specific (Hibernate) query hints. HQL supports SQL-like restriction, projection, joins, subselects, and function calls. JPA QL supports SQL-like restriction, projection, joins, subselects, and function calls subset of HQL. In the next chapter we focus on more advanced query techniques, such as programmatic generation of complex queries with the Criteria API and embedding of native SQL queries. We ll also talk about the query cache and when you should enable it.
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

Joins, reporting queries, and (My web server) subselects ANY The expression

Monday, May 26th, 2008

Joins, reporting queries, and subselects ANY The expression evaluates to true if the comparison is true for some (any) value in the result of the subquery. If the subquery result is empty or no value satisfies the comparison, it evaluates to false. The keyword SOME is a synonym for ANY. IN This binary comparison operator can compare a list of values against the result of a subquery and evaluates to true if all values are found in the result. For example, this query returns items where all bids are less than 100: from Item i where 100 > all ( select b.amount from i.bids b ) The next query returns all the others, items with bids greater than 100: from Item i where 100 <= any ( select b.amount from i.bids b ) This query returns items with a bid of exactly 100: from Item i where 100 = some ( select b.amount from i.bids b ) So does this one: from Item i where 100 in ( select b.amount from i.bids b ) HQL supports a shortcut syntax for subqueries that operate on elements or indices of a collection. The following query uses the special HQL elements() function: List result = session.createQuery("from Category c" + " where :givenItem in elements(c.items)") .setEntity("givenItem", item) .list() The query returns all categories to which the item belongs and is equivalent to the following HQL (and valid JPA QL), where the subquery is more explicit: List result = session.createQuery( "from Category c where :givenItem in (select i from c.items i)" ) .setEntity("item", item) .list(); Along with elements(), HQL provides indices(), maxelement(), minelement(), maxindex(), minindex(), and size(), each of which is equivalent to a certain correlated subquery against the passed collection. Refer to the Hibernate documentation for more information about these special functions; they re rarely used.
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

CHAPTER 14 Querying with HQL and JPA QL (Web design company)

Sunday, May 25th, 2008

CHAPTER 14 Querying with HQL and JPA QL FROM clause. Subselects in the SELECT clause are also not supported in the query language, but can be mapped to properties with a formula, as shown in Inverse joined properties in chapter 8, section 8.1.3. (Some platforms supported by Hibernate don t implement SQL subselects. Hibernate supports subselects only if the SQL database management system provides this feature.) Correlated and uncorrelated nesting The result of a subquery may contain either a single row or multiple rows. Typically, subqueries that return single rows perform aggregation. The following sub- query returns the total number of items sold by a user; the outer query returns all users who have sold more than 10 items: from User u where 10 < ( select count(i) from u.items i where i.successfulBid is not null ) This is a correlated subquery it refers to an alias (u) from the outer query The next subquery is an uncorrelated subquery: from Bid bid where bid.amount + 1 >= ( select max(b.amount) from Bid b ) The subquery in this example returns the maximum bid amount in the entire system; the outer query returns all bids whose amount is within one (dollar) of that amount. Note that in both cases, the subquery is enclosed in parentheses. This is always required. Uncorrelated subqueries are harmless, and there is no reason to not use them when convenient, although they can always be rewritten as two queries (they don t reference each other). You should think more carefully about the performance impact of correlated subqueries. On a mature database, the performance cost of a simple correlated subquery is similar to the cost of a join. However, it isn t necessarily possible to rewrite a correlated subquery using several separate queries. Quantification If a subquery returns multiple rows, it s combined with quantification. ANSI SQL, HQL, and JPA QL define the following quantifiers: ALL The expression evaluates to true if the comparison is true for all values in the result of the subquery. It evaluates to false if a single value of the subquery result fails the comparison test.
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

Joins, reporting queries, and subselects (perhaps also the (Web design)

Saturday, May 24th, 2008

Joins, reporting queries, and subselects (perhaps also the second-level cache) and manage uniqueness, and so on. If you ever wish to avoid the overhead of managing the persistence context cache, report queries give you a way to do this. The overhead of a Hibernate report query compared to direct SQL/JDBC isn t usually measurable, even in unrealistic extreme cases, like loading one million objects from a local database without network latency. Report queries using projection in HQL and JPA QL let you specify which prop erties you wish to retrieve. For report queries, you aren t selecting entities in man aged state, but only properties or aggregated values: select user.lastname, count(user) from User user group by user.lastname This query doesn t return persistent entity instances, so Hibernate doesn t add any persistent object to the persistence context cache. This means that no object must be watched for dirty state either. Therefore, reporting queries result in faster release of allocated memory, because objects aren t kept in the persistence context cache until the context is closed they may be garbage collected as soon as they re dereferenced by the application, after executing the report. Almost always, these considerations are extremely minor, so don t go out and rewrite all your read-only transactions to use report queries instead of transactional, cached, and managed objects. Report queries are more verbose and (arguably) less object-oriented. They also make less efficient use of Hibernate s caches, which is much more important once you consider the overhead of remote communication with the database in production systems. You should wait until you find a case where you have a real performance problem before using this optimization. You can already create really complex HQL and JPA QL queries with what you ve seen so far. Even more advanced queries may include nested statements, known as subselects. 14.3.3 Using subselects An important and powerful feature of SQL is subselects. A subselect is a select query embedded in another query, usually in the SELECT, FROM, or WHERE clauses. HQL and JPA QL support subqueries in the WHEREclause. Subselects in the FROM clause aren t supported by HQL and JPA QL (although the specification lists them as a possible future extension) because both languages have no transitive closure. The result of a query may not be tabular, so it can t be reused for selection in a
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

CHAPTER 14 Querying with HQL and JPA QL

Friday, May 23rd, 2008

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.