Example :
Define your entity class and use the @NamedQuery (or @NamedQueries with multiple @NamedQuery's) annotation to define each named query.
@Entity@NamedQueries({@NamedQuery(name="Product.findAllProducts", queryString="from Product pro"),@NamedQuery(name="Product.findAllProductsByProductId",queryString="from Product pro where pro.id = :productId"),@NamedQuery(name="Product.findAllProductsByProductName", queryString="from Product pro where pro.name = :productName"),@NamedQuery(name="Product.findAllProductsByProductPrice", queryString="from Product pro where pro.price between :minPrice and :maxPrice")})public class Product { ... }
An alternative to using the Entity and NamedQuery annotations is to define the named queries in the hibernate XML configuration mapping files. An example is below.
Note the use of the > in the last query. Remember that XML doesn't like <, > and & characters, so you have to escape them.<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.javalobby.tnt.hibernate">
<class name="Pet">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<many-to-one name="owner" column="owner_id" class="Owner"/>
</class>
<class name="Owner" batch-size="50">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<set name="pets" fetch="subselect">
<key column="owner_id" />
<one-to-many class="Pet"/>
</set>
</class>
<query name="all.owners">from Owner</query>
<query name="owner.by.pet.name">select pet.owner from Pet as pet where pet.name=?</query>
<query name="owners.with.multiple.pets">from Owner as owner where size(owner.pets) > 0</query>
</hibernate-mapping>
import java.util.List;
import org.hibernate.*;
public class LazyTest {
public static void main(String[] args) {
Session s = HibernateSupport.currentSession();
try {
Query q = s.getNamedQuery("all.owners");
printOwners(q);
Query q2 = s.getNamedQuery("owner.by.pet.name");
q2.setString(0, "Satchel"); // set parameters like usual
printOwners(q2);
Query q3 = s.getNamedQuery("owners.with.multiple.pets");
printOwners(q3);
}
finally {
HibernateSupport.closeSession(s);
}
}
/** * @param q */
private static void printOwners(Query q) {
List<Owner> l = q.list();
for(Owner owner : l) {
System.out.println("Owner: " + owner.getName());
for(Pet pet : owner.getPets()) {
System.out.println("\tPet: " + pet.getName());
}
}
}
}
Posted in: