Welcome to our Secure Development Tips blog

Every other week, we provide expert tech tips on how to build and deploy secure applications.  These best practices, derived from Security Innovation’s assessments of the worlds’ most dominant software applications,  are taken directly from our TeamMentor product, which includes more than 3,500 guidance assets and articles on secure software design, coding and testing.    

Subscribe by Email

Your email:

Secure Development Tips

a blog with tips relating to secure application development, from Security Innovation's eknowledge database, TeamMentor

Current Articles | RSS Feed RSS Feed

Use Named Queries with Hibernate

  
  

Applies to

  • Java web-based applications using Hibernate

Summary

Executing Named Queries using Hibernate.

Objectives

Use Hibernate named queries to perform database operations safely.

Scenarios

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.

Solution Example

To use named queries with Hibernate:

1. Define the entity class and the named queries. Define your entity class and use the @NamedQuery (or @NamedQueries with multiple @NamedQuery's) annotation to define each named query. The examples below are straightforward.

@Entity

@NamedQuery(

    name="Product.findAllProductsByProductName",

    queryString="from Product pro WHERE pro.name = :productName"

)

 

public class Product {

    ...

}

 

@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 {

    ...

}

2. Consider defining named queries in XML configuration files. 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.

<!-- product.hbm.xml -->

<hibernate-mapping>

    <class name="com.myapp.domain.Product" table="Product">

          <id ...>

          <property ...>

          <property ...>

          <property ...>

          ...

    </class>

    <query name="Product.findAllProductsByProductName">

          <![CDATA[from Product pro where pro.name = :productName]]>

    </query>

    <query name="Product.findAllProductsByProductPrice">

          <![CDATA[from Product pro where pro.price between :minPrice and :maxPrice]]>

    </query>

    ....

</hibernate-mapping>

3. Use the defined named queries in code. If there is a need for dynamic data, use the parameter binding mechanism included in the query implementation.

--------------------------

Example using dynamic data

--------------------------

//get hibernate session

Session session = ...;

//get dynamic data

//request parameters should be validated before use - this is a simple example

String productName = request.getParameter("product_name");

//use entity manager to retrieve named query

Query queryProductsByName = session.createNamedQuery("Product.findAllProductsByProductName");

//set dynamic data for query

queryProductsByName.setString("productName", productName);

//execute query and get results

List products = queryProductsByName.list();

--------------------------

Example without using dynamic data

--------------------------

//get hibernate session

Session session = ...;

//use entity manager to retrieve named query

Query queryProducts = session.createNamedQuery("Product.findAllProducts", Product.class);

//execute query and get results

List products = queryProducts.list();

The examples above show how to use named queries within Hibernate to create an environment where the queries are defined closely with the data they are operating against and that are safely used by requiring bound parameters for dynamic data. The use of other types of queries works in an identical manner, such as delete, update, insert, etc.

See Also

Java Data Access Guidelines

Java Data Access Checklists

Java Data Access Code Examples

Use Named Queries with Java Persistence API (JPA)

Comments

Post Comment
Name
 *
Email
 *
Website (optional)
Comment
 *

Allowed tags: <a> link, <b> bold, <i> italics