Photoshop web design - Creating and running queries To obtain a Criteria
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.