@AdditionalCriteria

Use @AdditionalCriteria to define parameterized views on data.

You can define additional criteria on entities or mapped superclass. When specified at the mapped superclass level, the additional criteria definition applies to all inheriting entities, unless those entities define their own additional criteria, in which case those defined for the mapped superclass are ignored.

Additional criteria can provide an additional filtering mechanism for queries. This filtering option, for example, allows you to use an existing additional JOIN expression defined for the entity or mapped superclass and allows you to pass parameters to it.

Set additional criteria parameters through properties on the entity manager factory or on the entity manager. Properties set on the entity manager override identically named properties set on the entity manager factory. Properties must be set on an entity manager before executing a query. Do not change the properties for the lifespan of the entity manager.

Note:

Additional criteria are not supported with native SQL queries.

Examples

Specify additional criteria using the @AdditionalCriteria annotation or the <additional-criteria> element. The additional criteria definition supports any valid JPQL string and must use this as an alias to form the additional criteria. For example:

@AdditionalCriteria("this.address.city IS NOT NULL")

Example 2-1 shows additional criteria defined for the entity Employee and then shows the parameters for the additional criteria set on the entity manager.

In a multitenancy environment, tenants (users, clients, organizations, applications) can share database tables, but the views on the data are restricted so that tenants have access only to their own data. You can use additional criteria to configure such restrictions.

Note:

In most cases, you use the @Multitenant annotation in multitenancy environments instead, as shown .

Example 2-3 Multitenancy Example 1

The following example restricts the data for a Billing client, such as a billing application or billing organization:

@AdditionalCriteria("this.tenant = 'Billing'")

Example 2-4 Multitenancy Example 2

The following example could be used in an application used by multiple tenants at the same time. The additional criteria is defined as:

@AdditionalCriteria("this.tenant = :tenant")

When the tenant acquires its EntityManagerFactory or EntityManager, the persistence/entity manager property tenant is set to the name of the tenant acquiring it. For example,

For a shared table, there may be inheritance in the table but not in the object model. For example, a SavingsAccount class may be mapped to an ACCOUNT table, but the ACCOUNT table contains both savings account data (SAVINGS) and checking account (CHECKING) data. You can use additional criteria to filter out the checking account data.