Other‎ > ‎

Hibernate Filters

Seam makes it possible to install hibernate filters automatically for each query. If this is not desired they can still be manually activated (see hibernate docs for examples)

The following code snippets show what is required to have Seam add a filter to each request.

Seam Confiuration


        name="entityManager" auto-create="true"

    <persistence:filter name="organizationFilter"
        enabled="#{identity.loggedIn and !(empty credentials.organization)}">

This works well as each query performed using the above EntityManager will be restricted to the organization that the current user belongs to. There are times when this is not the desired behavior. For such situations you can define an additional EntityManager in your components.xml as shown below.

components.xml (optional configuration)

        name="unrestrictedEntityManager" auto-create="true"
        persistence-unit-jndi-name="java:/risingstarsEntityManagerFactories" />

The second EntityManager can be injected into your Seam components like this:

    private EntityManager unrestrictedEntityManager;

Or used in other components in your components.xml like this:

        entity-manager="#{unrestrictedEntityManager}" />

Hibernate Filter Definition

Often, as is the case with this organization_filter, we want to use the same filter definition in multiple entity classes. To do this you can add the definition at the package level:


 * Copyright Software Factory - 2009
@FilterDef(name = "organization_filter", defaultCondition = "organization_id = :org_id", parameters = @org.hibernate.annotations.ParamDef(name = "org_id", type = "java.lang.Long"))
package nz.co.softwarefactory.risingstars.model;

import org.hibernate.annotations.FilterDef;

Note: The parameter defined here (org_id) must match the parameter defined in your components.xml and any columns referenced in the defaultCondition are sql column names NOT entity field names.

Finally in your entity class you need to declare the filter you are using.

 * Copyright Software Factory - 2009
package nz.co.softwarefactory.model;

import java.io.Serializable;

import javax.persistence.Entity;

import javax.persistence.Table;

import org.hibernate.annotations.Filter;

 * Business Description: An {@link Employee} represents a member of staff for the organization.
 * @author craig
@Filter(name = "organization_filter")
@Table(name = "employee")
public class Employee implements Serializable {
   //Normal class stuff here

Note: the filter name (organization_filter) corresponds to the filter name in your package-info.java and to the <persistence:name> element in your components.xml NOT the name of your filter component defined in your components.xml