Simple web server - CHAPTER 15 Advanced query options Criterion emailEq =
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.