Named Queries with Hibernate

Hibernate named queries provide a data access and manipulation mechanism that closely ties the query content to the Java code defining the objects that the query is executing against. It also removes the actual query language from Java code, which is a common tactic and creates certain maintainability issues. A security related advantage to named queries is that dynamic data must be bound, which prevents SQL injection attacks. The code below shows how to both define and use named queries in Hibernate.


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.

    <?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) &gt; 0</query> 
    </hibernate-mapping>
Note the use of the > in the last query. Remember that XML doesn't like <, > and & characters, so you have to escape them.

    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());  
    }  
    }


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email