Yahoo web space - CHAPTER 14 Querying with HQL and JPA QL
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.