Archive for March, 2008

Yahoo web space - CHAPTER 14 Querying with HQL and JPA QL

Monday, March 31st, 2008

CHAPTER 14 Querying with HQL and JPA QL Query q = em.createQuery(queryString) .setParameter(”search”, searchString) .setParameter(”minDate”, mDate, TemporalType.DATE); The setParameter() method is a generic operation that can bind all types of arguments, it only needs a little help for temporal types (the engine needs to know if you want only the date, time, or a full timestamp bound). Java Persistence supports only this method for binding of parameters (Hibernate, by the way, has it too). Hibernate, on the other hand, offers many other methods, some of them for completeness, others for convenience, that you can use to bind arguments to query parameters. Using Hibernate parameter binding You ve called setString() and setDate() to bind arguments to query parameters. The native Hibernate Query interface provides similar convenience methods for binding arguments of most of the Hibernate built-in types: everything from setInteger() to setTimestamp() and setLocale(). They re mostly optional; you can rely on the setParameter() method to figure out the right type automatically (except for temporal types). A particularly useful method is setEntity(), which lets you bind a persistent entity (note that setParameter() is smart enough to understand even that automatically): session.createQuery(”from Item item where item.seller = :seller”) .setEntity(”seller”, theSeller); However, there is also a generic method that allows you to bind an argument of any Hibernate type: String queryString = “from Item item” + ” where item.seller = :seller and” + ” item.description like :desc”; session.createQuery(queryString) .setParameter( “seller”, theSeller, Hibernate.entity(User.class) ) .setParameter( “desc”, description, Hibernate.STRING ); This works even for custom user-defined types, like MonetaryAmount: Query q = session.createQuery(”from Bid where amount > :amount”); q.setParameter( “amount”, givenAmount, Hibernate.custom(MonetaryAmountUserType.class) );
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

Creating and running queries (1 on 1 web hosting) As you can see,

Sunday, March 30th, 2008

Creating and running queries As you can see, the original queryString is no longer a simple search for a string but also executes a stored procedure in the database! The quote characters aren t escaped; hence the call to the stored procedure is another valid expression in the query. If you write a query like this, you open up a major security hole in your application by allowing the execution of arbitrary code on your database. This is known as an SQL injection security issue. Never pass unchecked values from user input to the database! Fortunately, a simple mechanism prevents this mistake. The JDBC driver includes functionality for safely binding values to SQL parameters. It knows exactly what characters in the parameter value to escape, so that the previous vulnerability doesn t exist. For example, the quote characters in the given search are escaped and are no longer treated as control characters but as a part of the search string value. Furthermore, when you use parameters, the database is able to efficiently cache precompiled prepared statements, improving performance significantly. There are two approaches to parameter binding: using positional or using named parameters. Hibernate and Java Persistence support both options, but you can t use both at the same time for a particular query. With named parameters, you can rewrite the query as String queryString = “from Item item where item.description like :search”; The colon followed by a parameter name indicates a named parameter. Then, bind a value to the search parameter: Query q = session.createQuery(queryString) .setString(”search”, searchString); Because searchString is a user-supplied string variable, you call the setString() method of the Query interface to bind it to the named parameter (:search). This code is cleaner, much safer, and performs better, because a single compiled SQL statement can be reused if only bind parameters change. Often, you ll need multiple parameters: String queryString = “from Item item” + ” where item.description like :search” + ” and item.date > :minDate”; Query q = session.createQuery(queryString) .setString(”search”, searchString) .setDate(”minDate”, mDate); The same query and code looks slightly different in Java Persistence:
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

Florida web design - CHAPTER 14 Querying with HQL and JPA QL

Saturday, March 29th, 2008

CHAPTER 14 Querying with HQL and JPA QL Starting from the fortieth object, you retrieve the next 20 objects. Note that there is no standard way to express pagination in SQL Hibernate knows the tricks to make this work efficiently on your particular database. You can even add this flexible pagination option to an SQL query. Hibernate will rewrite your SQL for pagination: Query sqlQuery = session.createSQLQuery(”select {u.*} from USERS {u}”) .addEntity(”u”, User.class); sqlQuery.setFirstResult(40); sqlQuery.setMaxResults(20); You may use the method-chaining coding style (methods return the receiving object instead of void) with the Query and Criteria interfaces, rewriting the two previous examples as follows: Query query = session.createQuery(”from User u order by u.name asc”) .setMaxResults(10); Criteria crit = session.createCriteria(User.class) .addOrder( Order.asc(”name”) ) .setFirstResult(40) .setMaxResults(20); Chaining method calls is less verbose and is supported by many Hibernate APIs. The Java Persistence query interfaces also support pagination and method chaining for JPA QL and native SQL queries with the javax.persistence.Query interface: Query query = em.createQuery(”select u from User u order by u.name asc”) .setFirstResult(40) .setMaxResults(20); Next in preparing your query is the setting of any runtime parameters. Considering parameter binding Without runtime parameter binding, you have to write bad code: String queryString = “from Item i where i.description like ‘” + search + “‘”; List result = session.createQuery(queryString).list(); You should never write this code because a malicious user could search for the following item description that is, by entering the value of search in a search dialog box as foo’ and callSomeStoredProcedure() and ‘bar’ = ‘bar
You want to have a cheap webhost for your apache application, then check apache web hosting services.

Photoshop web design - Creating and running queries To obtain a Criteria

Saturday, March 29th, 2008

Creating and running queries To obtain a Criteria instance, call createCriteria(), passing the class of the objects you want the query to return. This is also called the root entity of the criteria query, the User in this example: Criteria crit = session.createCriteria(User.class); The Criteria instance may be used in the same way as a Query object but it s also used to construct the object-oriented representation of the query, by adding Criterion instances and navigating associations to new Criterias. With the Java Persistence API, your starting point for queries is the EntityManager. To create a javax.persistence.Query instance for JPA QL, call create- Query(): Query ejbQuery = em.createQuery(”select u from User u”); To create a native SQL query, use createNativeQuery(): Query sqlQuery = session.createNativeQuery( “select u.USER_ID, u.FIRSTNAME, u.LASTNAME from USERS u”, User.class ); The way you define the returned objects from a native query is slightly different than in Hibernate (there are no placeholders in the query here). After you ve created the query, you prepare it for execution by setting various options. Paging the result A commonly used technique is pagination. Users may see the result of their search request (for example, for specific Items) as a page. This page shows a limited subset (say, 10 Items) at a time, and users can navigate to the next and previous pages manually. In Hibernate, Query and Criteria interfaces support this pagination of the query result: Query query = session.createQuery(”from User u order by u.name asc”); query.setMaxResults(10); The call to setMaxResults(10) limits the query resultset to the first 10 objects (rows) returned by the database. In this Criteria query, the requested page starts in the middle of the resultset: Criteria crit = session.createCriteria(User.class); crit.addOrder( Order.asc(”name”) ); crit.setFirstResult(40); crit.setMaxResults(20);
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

CHAPTER 14 Querying with HQL and JPA QL (Web hosting top)

Friday, March 28th, 2008

CHAPTER 14 Querying with HQL and JPA QL 1 Create the query, with any arbitrary restriction or projection of data that you want to retrieve. 2 Bind runtime arguments to query parameters; the query can be reused with changing settings. 3 Execute the prepared query against the database and retrieval of data. You can control how the query is executed and how data should be retrieved into memory (all at once or piecemeal, for example). Hibernate and Java Persistence offer query interfaces and methods on these interfaces to prepare and execute arbitrary data retrieval operations. 14.1.1 Preparing a query The org.hibernate.Query and org.hibernate.Criteria interfaces both define several methods for controlling execution of a query. In addition, Query provides methods for binding concrete values to query parameters. To execute a query in your application, you need to obtain an instance of one of these interfaces, using the Session. Java Persistence specifies the javax.persistence.Query interface. The standardized interface isn t as rich as the native Hibernate API, but offers all necessary methods to execute a query in different ways and to bind arguments to query parameters. Unfortunately, the useful Hibernate Criteria API has no equivalent in Java Persistence, although it s highly likely that a similar query interface will be added in a future version of the standard. Creating a query object To create a new Hibernate Query instance, call either createQuery() or create- SQLQuery() on a Session. The createQuery() method prepares an HQL query: Query hqlQuery = session.createQuery(”from User”); createSQLQuery() is used to create an SQL query using the native syntax of the underlying database: Query sqlQuery = session.createSQLQuery( “select {user.*} from USERS {user}” ).addEntity(”user”, User.class); In both cases, Hibernate returns a newly instantiated Query object that may be used to specify exactly how a particular query should be executed and to allow execution of the query. So far, no SQL has been sent to the database.
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

Creating and running queries Queries are the most (Best web site)

Thursday, March 27th, 2008

Creating and running queries Queries are the most interesting part of writing good data access code. A complex query may require a long time to get right, and its impact on the performance of the application can be tremendous. On the other hand, writing queries becomes much easier with more experience, and what seemed difficult at first is only a matter of knowing some of the more advanced features. If you ve been using handwritten SQL for a number of years, you may be con cerned that ORM will take away some of the expressiveness and flexibility that you re used to. This isn t the case with Hibernate and Java Persistence. Hibernate s powerful query facilities allow you to express almost everything you commonly (or even uncommonly) need to express in SQL, but in object-ori ented terms using classes and properties of classes. We ll show you the differences between native Hibernate queries and the standardized subset in Java Persistence. You may also use this chapter as a reference; hence some sections are written in a less verbose style but show many small code examples for different use cases. We also sometimes skip optimizations in the CaveatEmptor application for better readability. For example, instead of referring to the MonetaryAmount value type, we use a BigDecimal amount in comparisons. First, we show you how queries are executed. Don t let yourself be distracted by the queries; we discuss them soon. 14.1 Creating and running queries Let s start with a few examples so you understand the basic usage. In earlier chapters, we mentioned that there are three ways to express queries in Hibernate: Hibernate Query Language (HQL), and the subset standardized as JPA QL: session.createQuery(”from Category c where c.name like ‘Laptop%’”); entityManager.createQuery( “select c from Category c where c.name like ‘Laptop%’” ); Criteria API for query by criteria (QBC) and query by example (QBE): session.createCriteria(Category.class) .add( Restrictions.like(”name”, “Laptop%”) ); Direct SQL with or without automatic mapping of resultsets to objects: session.createSQLQuery( “select {c.*} from CATEGORY {c} where NAME like ‘Laptop%’” ).addEntity(”c”, Category.class); A query must be prepared in application code before execution. So, querying involves several distinct steps:
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

Querying with HQL (Cpanel web hosting) and JPA QL This chapter

Wednesday, March 26th, 2008

Querying with HQL and JPA QL This chapter covers Understanding the various query options Writing HQL and JPA QL queries Joins, reporting queries, subselects 614
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

Summary ment that must be executed. You especially (Web hosting reseller)

Tuesday, March 25th, 2008

Summary ment that must be executed. You especially want to avoid the n+1 selects and Cartesian product issues we examined in detail, using various optimization strategies. The second half of this chapter introduced caching with the theory behind caching and a checklist you can apply to find out which classes and collections are good candidates for Hibernate s optional second-level cache. You then configured and enabled second-level caching for a few classes and collections with the local EHCache provider, and a cluster-enabled JBoss Cache. Table 13.2 shows a summary you can use to compare native Hibernate features and Java Persistence. Table 13.2 Hibernate and JPA comparison chart for chapter 13 Hibernate Core Java Persistence and EJB 3.0 Hibernate supports fetch-plan definition with lazy loading through proxies or based on interception. Hibernate implements a Java Persistence provider with proxy or interception-based lazy loading. Hibernate allows fine-grained control over fetch-plan and fetching strategies. Java Persistence standardizes annotations for fetch plan declaration, Hibernate extensions are used for fine-grained fetching strategy optimization. Hibernate provides an optional second-level class and collection data cache, configured in a Hibernate configuration file or XML mapping files. Use Hibernate annotations for declaration of the cache concurrency strategy on entities and collections. The next chapters deal exclusively with querying and how to write and execute HQL, JPA QL, SQL, and Criteria queries with all Hibernate and Java Persistence interfaces.
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

CHAPTER 13 Optimizing fetching and caching } }

Sunday, March 23rd, 2008

CHAPTER 13 Optimizing fetching and caching } } tx.commit(); session.close(); Setting CacheMode.IGNORE tells Hibernate not to interact with the second-level cache, in this particular Session. The available options are as follows: CacheMode.NORMAL The default behavior. CacheMode.IGNORE Hibernate never interacts with the second-level cache except to invalidate cached items when updates occur. CacheMode.GET Hibernate may read items from the second-level cache, but it won t add items except to invalidate items when updates occur. CacheMode.PUT Hibernate never reads items from the second-level cache, but it adds items to the cache as it reads them from the database. CacheMode.REFRESH Hibernate never reads items from the second-level cache, but it adds items to the cache as it reads them from the database. In this mode, the effect of hibernate.cache.use_minimal_puts is bypassed, in order to force a cache refresh in a replicated cluster cache. Good use cases for any cache modes except NORMAL and IGNORE are rare. This completes our discussion of the first- and second-level caches in a Hibernate application. We d like to repeat a statement we made at the beginning of this section: Your application should perform satisfactorily without the second-level cache. You ve only cured the symptoms, not the actual problem if a particular procedure in your application is running in 2 instead of 50 seconds with the second- level cache enabled. Customization of the fetch plan and fetching strategy is always your first optimization step; then, use the second-level cache to make your application snappier and to scale it to the concurrent transaction load it will have to handle in production. 13.5 Summary In this chapter, you created a global fetch plan and defined which objects and collections should be loaded into memory at all times. You defined the fetch plan based on your use cases and how you want to access associated entities and iterate through collections in your application. Next, you selected the right fetching strategy for your fetch plan. Your goal is to minimize the number of SQL statements and the complexity of each SQL state
We recommend high quality webhost to host and run your jsp application: christian web host services.

Caching in practice 13.4.5 Controlling the second-level cache (Starting a web site)

Saturday, March 22nd, 2008

Caching in practice 13.4.5 Controlling the second-level cache Hibernate has some useful methods that can help you test and tune your cache. Consider the global configuration switch for the second-level cache, hibernate. cache.use_second_level_cache. By default, any element in your mapping files (or in hibernate.cfg.xml, or an annotation) triggers the second-level cache and loads the cache provider at startup. If you want to disable the second- level cache globally without removing the cache mapping elements or annotations, set this configuration property to false. Just as the Session and EntityManager provide methods for controlling the persistence context first-level cache programmatically, so does the SessionFactory for the second-level cache. In a JPA application, you have to get access to the underlying internal SessionFactory, as described in chapter 2, section 2.2.4, Switching to Hibernate interfaces. You can call evict() to remove an element from the second-level cache by specifying the class and the object identifier value: SessionFactory.evict( Category.class, new Long(123) ); You may also evict all elements of a certain class or only evict a particular collection role by specifying a region name: SessionFactory.evict(”auction.model.Category”); You ll rarely need these control mechanisms. Also note that eviction of the sec ond-level cache is nontransactional, that is, the cache region isn t locked during eviction. Hibernate also offers CacheMode options that can be activated for a particular Session. Imagine that you want to insert many objects into the database in one Session. You need to do this in batches, to avoid memory exhaustion every object is added to the first-level cache. However, it s also added to the second-level cache, if enabled for the entity class. A CacheMode controls the interaction of Hibernate with the second-level cache: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.setCacheMode(CacheMode.IGNORE); for ( int i=0; i<100000; i++ ) { Item item = new Item(...); session.save(item); if ( i % 100 == 0 ) { session.flush(); session.clear();
Check Tomcat Web Hosting services for best quality webspace to host your web application.