Hibernate.org Community Documentation

- Précédent
- Suivant

## Chapitre 23. Additional modules

Hibernate Core also offers integration with some external modules/projects. This includes Hibernate Validator the reference implementation of Bean Validation (JSR 303) and Hibernate Search.

## 23.1. Bean Validation

Bean Validation standardizes how to define and declare domain model level constraints. You can, for example, express that a property should never be null, that the account balance should be strictly positive, etc. These domain model constraints are declared in the bean itself by annotating its properties. Bean Validation can then read them and check for constraint violations. The validation mechanism can be executed in different layers in your application without having to duplicate any of these rules (presentation layer, data access layer). Following the DRY principle, Bean Validation and its reference implementation Hibernate Validator has been designed for that purpose.

The integration between Hibernate and Bean Validation works at two levels. First, it is able to check in-memory instances of a class for constraint violations. Second, it can apply the constraints to the Hibernate metamodel and incorporate them into the generated database schema.

Each constraint annotation is associated to a validator implementation responsible for checking the constraint on the entity instance. A validator can also (optionally) apply the constraint to the Hibernate metamodel, allowing Hibernate to generate DDL that expresses the constraint. With the appropriate event listener, you can execute the checking operation on inserts, updates and deletes done by Hibernate.

When checking instances at runtime, Hibernate Validator returns information about constraint violations in a set of `ConstraintViolation`s. Among other information, the `ConstraintViolation` contains an error description message that can embed the parameter values bundle with the annotation (eg. size limit), and message strings that may be externalized to a `ResourceBundle`.

### 23.1.1. Adding Bean Validation

To enable Hibernate's Bean Validation integration, simply add a Bean Validation provider (preferably Hibernate Validation 4) on your classpath.

### 23.1.2. Configuration

By default, no configuration is necessary.

The `Default` group is validated on entity insert and update and the database model is updated accordingly based on the `Default` group as well.

You can customize the Bean Validation integration by setting the validation mode. Use the `javax.persistence.validation.mode` property and set it up for example in your `persistence.xml` file or your `hibernate.cfg.xml` file. Several options are possible:

- `auto` (default): enable integration between Bean Validation and Hibernate (callback and ddl generation) only if Bean Validation is present in the classpath.

- `none`: disable all integration between Bean Validation and Hibernate

- `callback`: only validate entities when they are either inserted, updated or deleted. An exception is raised if no Bean Validation provider is present in the classpath.

- `ddl`: only apply constraints to the database schema when generated by Hibernate. An exception is raised if no Bean Validation provider is present in the classpath. This value is not defined by the Java Persistence spec and is specific to Hibernate.

## Note

You can use both `callback` and `ddl` together by setting the property to `callback, dll`

    <persistence ...>

      <persistence-unit ...>

        ...

        <properties>

          <property name="javax.persistence.validation.mode"

                    value="callback, ddl"/>

        </properties>

      </persistence-unit>

    </persistence>

This is equivalent to `auto` except that if no Bean Validation provider is present, an exception is raised.

If you want to validate different groups during insertion, update and deletion, use:

- `javax.persistence.validation.group.pre-persist`: groups validated when an entity is about to be persisted (default to `Default`)

- `javax.persistence.validation.group.pre-update`: groups validated when an entity is about to be updated (default to `Default`)

- `javax.persistence.validation.group.pre-remove`: groups validated when an entity is about to be deleted (default to no group)

- `org.hibernate.validator.group.ddl`: groups considered when applying constraints on the database schema (default to `Default`)

Each property accepts the fully qualified class names of the groups validated separated by a comma (,)

Exemple 23.1. Using custom groups for validation

    <persistence ...>

      <persistence-unit ...>

        ...

        <properties>

          <property name="javax.persistence.validation.group.pre-update"

                    value="javax.validation.group.Default, com.acme.group.Strict"/>

          <property name="javax.persistence.validation.group.pre-remove"

                    value="com.acme.group.OnDelete"/>

          <property name="org.hibernate.validator.group.ddl"

                    value="com.acme.group.DDL"/>

        </properties>

      </persistence-unit>

    </persistence>

## Note

You can set these properties in `hibernate.cfg.xml`, `hibernate.properties` or programmatically.

### 23.1.3. Catching violations

If an entity is found to be invalid, the list of constraint violations is propagated by the `ConstraintViolationException` which exposes the set of `ConstraintViolation`s.

This exception is wrapped in a `RollbackException` when the violation happens at commit time. Otherwise the `ConstraintViolationException` is returned (for example when calling `flush()`. Note that generally, catchable violations are validated at a higher level (for example in Seam / JSF 2 via the JSF - Bean Validation integration or in your business layer by explicitly calling Bean Validation).

An application code will rarely be looking for a `ConstraintViolationException` raised by Hibernate. This exception should be treated as fatal and the persistence context should be discarded (`EntityManager` or `Session`).

### 23.1.4. Database schema

Hibernate uses Bean Validation constraints to generate an accurate database schema:

- `@NotNull` leads to a not null column (unless it conflicts with components or table inheritance)

- `@Size.max` leads to a `varchar(max)` definition for Strings

- `@Min`, `@Max` lead to column checks (like `value <= max`)

- `@Digits` leads to the definition of precision and scale (ever wondered which is which? It's easy now with `@Digits` :) )

These constraints can be declared directly on the entity properties or indirectly by using constraint composition.

For more information check the Hibernate Validator reference documentation.

## 23.2. Hibernate Search

### 23.2.1. Description

Full text search engines like Apache Lucene™ are a very powerful technology to bring free text/efficient queries to applications. If suffers several mismatches when dealing with a object domain model (keeping the index up to date, mismatch between the index structure and the domain model, querying mismatch...) Hibernate Search indexes your domain model thanks to a few annotations, takes care of the database / index synchronization and brings you back regular managed objects from free text queries. Hibernate Search is using Apache Lucene under the cover.

### 23.2.2. Integration with Hibernate Annotations

Hibernate Search integrates with Hibernate Core transparently provided that the Hibernate Search jar is present on the classpath. If you do not wish to automatically register Hibernate Search event listeners, you can set `hibernate.search.autoregister_listeners` to false. Such a need is very uncommon and not recommended.

Check the Hibernate Search reference documentation for more information.

Copyright © 2004 Red Hat, Inc.

- PrécédentChapitre 22. Guide de la boîte à outils
- Niveau supérieur
- Sommaire
- SuivantChapitre 24. Exemple : père/fils