[[envers]]
== Envers
:sourcedir: ../../../../../test/java/org/hibernate/userguide/envers
:extrasdir: extras

[[envers-basics]]
=== Basics

To audit changes that are performed on an entity, you only need two things:

* the `hibernate-envers` jar on the classpath,
* an `@Audited` annotation on the entity.

[IMPORTANT]
====
Unlike in previous versions, you no longer need to specify listeners in the Hibernate configuration file.
Just putting the Envers jar on the classpath is enough because listeners will be registered automatically.
====

And that's all.
You can create, modify and delete the entities as always.

[IMPORTANT]
====
The use of JPA's `CriteriaUpdate` and `CriteriaDelete` bulk operations are not currently supported by Envers
due to how an entity's lifecycle events are dispatched. Such operations should be avoided as they're not
captured by Envers and lead to incomplete audit history.
====

If you look at the generated schema for your entities, or at the data persisted by Hibernate, you will notice that there are no changes.
However, for each audited entity, a new table is introduced - `entity_table_AUD`, which stores the historical data, whenever you commit a transaction.

[NOTE]
====
Envers automatically creates audit tables if `hibernate.hbm2ddl.auto` option is set to `create`, `create-drop` or `update`.
Appropriate DDL statements can also be generated with an Ant task in <<envers-generateschema>>.
====

Considering we have a `Customer` entity, when annotating it with the `Audited` annotation,
Hibernate is going to generate the following tables using the `hibernate.hbm2ddl.auto` schema tool:

[[envers-audited-mapping-example]]
.Basic Envers entity mapping
====
[source, JAVA, indent=0]
----
include::{sourcedir}/DefaultAuditTest.java[tags=envers-audited-mapping-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-audited-mapping-example.sql[]
----
====

Instead of annotating the whole class and auditing all properties, you can annotate only some persistent properties with `@Audited`.
This will cause only these properties to be audited.

Now, considering the previous `Customer` entity,
let's see how Envers auditing works when inserting, updating, and deleting the entity in question.

[[envers-audited-insert-example]]
.Auditing the entity `INSERT` operation
====
[source, JAVA, indent=0]
----
include::{sourcedir}/DefaultAuditTest.java[tags=envers-audited-insert-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-audited-insert-example.sql[]
----
====

[[envers-audited-update-example]]
.Auditing the entity `UPDATE` operation
====
[source, JAVA, indent=0]
----
include::{sourcedir}/DefaultAuditTest.java[tags=envers-audited-update-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-audited-update-example.sql[]
----
====

[[envers-audited-delete-example]]
.Auditing the entity `DELETE` operation
====
[source, JAVA, indent=0]
----
include::{sourcedir}/DefaultAuditTest.java[tags=envers-audited-delete-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-audited-delete-example.sql[]
----
====

The `REVTYPE` column value is taken from the https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/javadocs/org/hibernate/envers/RevisionType.html[`RevisionType`] Enum.

[[envers-revtype-column]]
.`REVTYPE` column values
[width="100%",cols="20%,20%,60%",]
|=================================
|Database column value |Associated `RevisionType` Enum value |Description
|0 | `ADD` |A database table row was inserted.
|1 | `MOD` |A database table row was updated.
|2 | `DEL` |A database table row was deleted.
|=================================

The audit (history) of an entity can be accessed using the `AuditReader` interface, which can be obtained by having an open `EntityManager` or `Session` via the `AuditReaderFactory`.

[[envers-audited-revisions-example]]
.Getting a list of revisions for the `Customer` entity
====
[source, JAVA, indent=0]
----
include::{sourcedir}/DefaultAuditTest.java[tags=envers-audited-revisions-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-audited-revisions-example.sql[]
----
====

Using the previously fetched revisions, we can now inspect the state of the `Customer` entity at that particular revision:

[[envers-audited-rev1-example]]
.Getting the first revision for the `Customer` entity
====
[source, JAVA, indent=0]
----
include::{sourcedir}/DefaultAuditTest.java[tags=envers-audited-rev1-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-audited-rev1-example.sql[]
----
====

When executing the aforementioned SQL query, there are two parameters:

revision_number::
The first parameter marks the revision number we are interested in or the latest one that exists up to this particular revision.
revision_type::
The second parameter specifies that we are not interested in `DEL` `RevisionType` so that deleted entries are filtered out.

The same goes for the second revision associated with the `UPDATE` statement.

[[envers-audited-rev2-example]]
.Getting the second revision for the `Customer` entity
====
[source, JAVA, indent=0]
----
include::{sourcedir}/DefaultAuditTest.java[tags=envers-audited-rev2-example]
----
====

For the deleted entity revision, Envers throws a `NoResultException` since the entity was no longer valid at that revision.

[[envers-audited-rev3-example]]
.Getting the third revision for the `Customer` entity
====
[source, JAVA, indent=0]
----
include::{sourcedir}/DefaultAuditTest.java[tags=envers-audited-rev3-example]
----
====

You can use the
https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/javadocs/org/hibernate/envers/query/AuditQueryCreator.html#forEntitiesAtRevision-java.lang.Class-java.lang.String-java.lang.Number-boolean-[`forEntitiesAtRevision(Class<T> cls, String entityName, Number revision, boolean includeDeletions)`]
method to get the deleted entity revision so that, instead of a `NoResultException`,
all attributes, except for the entity identifier, are going to be `null`.

[[envers-audited-rev4-example]]
.Getting the third revision for the `Customer` entity without getting a `NoResultException`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/DefaultAuditTest.java[tags=envers-audited-rev4-example]
----
====

See the https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/javadocs/org/hibernate/envers/AuditReader.html[Javadocs] for details on other functionality offered.

[[envers-configuration]]
=== Configuration Properties

It is possible to configure various aspects of Hibernate Envers behavior, such as table names, etc.

`*org.hibernate.envers.audit_table_prefix*`::
String that will be prepended to the name of an audited entity to create the name of the entity and that will hold audit information.

`*org.hibernate.envers.audit_table_suffix`* (default: `_AUD`)::
String that will be appended to the name of an audited entity to create the name of the entity and that will hold audit information.
+
If you audit an entity with a table name Person, in the default setting Envers will generate a `Person_AUD` table to store historical data.

`*org.hibernate.envers.revision_field_name*` (default: `REV`)::
Name of a field in the audit entity that will hold the revision number.

`*org.hibernate.envers.revision_type_field_name*` (default: `REVTYPE` )::
Name of a field in the audit entity that will hold the type of the revision (currently, this can be: `add`, `mod`, `del`).

`*org.hibernate.envers.revision_on_collection_change*` (default: `true` )::
Should a revision be generated when a not-owned relation field changes (this can be either a collection in a one-to-many relation or the field using `mappedBy` attribute in a one-to-one relation).

`*org.hibernate.envers.do_not_audit_optimistic_locking_field*` (default: `true` )::
When true, properties to be used for optimistic locking, annotated with `@Version`, will not be automatically audited (their history won't be stored; it normally doesn't make sense to store it).

`*org.hibernate.envers.store_data_at_delete*` (default: `false` )::
Should the entity data be stored in the revision when the entity is deleted (instead of only storing the id and all other properties as null).
+
This is not normally needed, as the data is present in the last-but-one revision.
Sometimes, however, it is easier and more efficient to access it in the last revision (then the data that the entity contained before deletion is stored twice).

`*org.hibernate.envers.default_schema*` (default: `null` - same schema as the table being audited)::
The default schema name that should be used for audit tables.
+
Can be overridden using the `@AuditTable( schema = "..." )` annotation.
+
If not present, the schema will be the same as the schema of the table being audited.

`*org.hibernate.envers.default_catalog*` (default: `null` - same catalog as the table being audited)::
The default catalog name that should be used for audit tables.
+
Can be overridden using the `@AuditTable( catalog = "..." )` annotation.
+
If not present, the catalog will be the same as the catalog of the normal tables.

`*org.hibernate.envers.audit_strategy*`(default: `org.hibernate.envers.strategy.DefaultAuditStrategy` )::
The audit strategy that should be used when persisting audit data.
The default stores only the revision, at which an entity was modified.
+
An alternative, the `org.hibernate.envers.strategy.ValidityAuditStrategy` stores both the start revision and the end revision.
Together these define when an audit row was valid, hence the name ValidityAuditStrategy.

`*org.hibernate.envers.audit_strategy_validity_end_rev_field_name*` (default: `REVEND`)::
The column name that will hold the end revision number in audit entities.
This property is only valid if the validity audit strategy is used.

`*org.hibernate.envers.audit_strategy_validity_store_revend_timestamp*`(default: `false` )::
Should the timestamp of the end revision be stored, until which the data was valid, in addition to the end revision itself.
This is useful to be able to purge old Audit records out of a relational database by using table partitioning.
+
Partitioning requires a column that exists within the table.
This property is only evaluated if the `ValidityAuditStrategy` is used.

`*org.hibernate.envers.audit_strategy_validity_revend_timestamp_field_name*`(default: `REVEND_TSTMP` )::
Column name of the timestamp of the end revision until which the data was valid.
Only used if the `ValidityAuditStrategy` is used, and `org.hibernate.envers.audit_strategy_validity_store_revend_timestamp` evaluates to true.

`*org.hibernate.envers.use_revision_entity_with_native_id*` (default: `true` )::
Boolean flag that determines the strategy of revision number generation.
Default implementation of revision entity uses native identifier generator.
+
If the current database engine does not support identity columns, users are advised to set this property to false.
+
In this case revision numbers are created by preconfigured `org.hibernate.id.enhanced.SequenceStyleGenerator`.
See: `org.hibernate.envers.DefaultRevisionEntity` and `org.hibernate.envers.enhanced.SequenceIdRevisionEntity`.

`*org.hibernate.envers.track_entities_changed_in_revision*` (default: `false` )::
Should entity types, that have been modified during each revision, be tracked.
The default implementation creates `REVCHANGES` table that stores entity names of modified persistent objects.
Single record encapsulates the revision identifier (foreign key to `REVINFO` table) and a string value.
For more information, refer to <<envers-tracking-modified-entities-revchanges>> and <<envers-tracking-modified-entities-queries>>.

`*org.hibernate.envers.global_with_modified_flag*` (default: `false`, can be individually overridden with `@Audited( withModifiedFlag = true )` )::
Should property modification flags be stored for all audited entities and all properties.
+
When set to true, for all properties an additional boolean column in the audit tables will be created, filled with information if the given property changed in the given revision.
+
When set to false, such column can be added to selected entities or properties using the `@Audited` annotation.
+
For more information, refer to <<envers-tracking-properties-changes>> and <<envers-tracking-properties-changes-queries>>.

`*org.hibernate.envers.modified_flag_suffix*` (default: `_MOD` )::
The suffix for columns storing "Modified Flags".
+
For example, a property called "age", will by default get modified flag with column name "age_MOD".

`*org.hibernate.envers.modified_column_naming_strategy*` (default: `org.hibernate.envers.boot.internal.LegacyModifiedColumnNamingStrategy` )::
The naming strategy to be used for modified flag columns in the audit metadata.

`*org.hibernate.envers.embeddable_set_ordinal_field_name*` (default: `SETORDINAL` )::
Name of column used for storing ordinal of the change in sets of embeddable elements.

`*org.hibernate.envers.cascade_delete_revision*` (default: `false` )::
While deleting revision entry, remove data of associated audited entities. Requires database support for cascade row removal.

`*org.hibernate.envers.allow_identifier_reuse*` (default: `false` )::
Guarantees proper validity audit strategy behavior when application reuses identifiers of deleted entities. Exactly one row with `null` end date exists for each identifier.

`*org.hibernate.envers.original_id_prop_name*` (default: `originalId` )::
Specifies the composite-id key property name used by the audit table mappings.

`*org.hibernate.envers.find_by_revision_exact_match*` (default: `false` )::
Specifies whether or not `AuditReader#find` methods which accept a revision-number argument are to find results based on fuzzy-match or exact-match behavior.
+
The old (legacy) behavior has always been to perform a fuzzy-match where these methods would return a match if any revision existed for the primary-key with a revision-number less-than or equal-to the revision method argument.
This behavior is great when you want to find the snapshot of a non-related entity based on another entity's revision number.
+
The new (optional) behavior when this option is enabled forces the query to perform an exact-match instead.
In order for these methods to return a non-`null` value, a revision entry must exist for the entity with the specified primary key and revision number; otherwise the result will be `null`.

[IMPORTANT]
====
The following configuration options have been added recently and should be regarded as experimental:

.  `org.hibernate.envers.track_entities_changed_in_revision`
.  `org.hibernate.envers.using_modified_flag`
.  `org.hibernate.envers.modified_flag_suffix`
.  `org.hibernate.envers.modified_column_naming_strategy`
.  `org.hibernate.envers.original_id_prop_name`
.  `org.hibernate.envers.find_by_revision_exact_match`
====

[[envers-additional-mappings]]
=== Additional mapping annotations

The name of the audit table can be set on a per-entity basis, using the `@AuditTable` annotation.
It may be tedious to add this annotation to every audited entity, so if possible, it's better to use a prefix/suffix.

If you have a mapping with secondary tables, audit tables for them will be generated in the same way (by adding the prefix and suffix).
If you wish to overwrite this behavior, you can use the `@SecondaryAuditTable` and `@SecondaryAuditTables` annotations.

If you'd like to override auditing behavior of some fields/properties inherited from `@MappedSuperclass` or in an embedded component,
you can apply the `@AuditOverride` annotation on the subtype or usage site of the component.

If you want to audit a relation mapped with `@OneToMany` and `@JoinColumn`,
please see <<envers-mappingexceptions>> for a description of the additional `@AuditJoinTable` annotation that you'll probably want to use.

If you want to audit a relation, where the target entity is not audited (that is the case for example with dictionary-like entities, which don't change and don't have to be audited),
just annotate it with `@Audited( targetAuditMode = RelationTargetAuditMode.NOT_AUDITED )`.
Then, while reading historic versions of your entity, the relation will always point to the "current" related entity.
By default Envers throws `javax.persistence.EntityNotFoundException` when "current" entity does not exist in the database.
Apply `@NotFound( action = NotFoundAction.IGNORE )` annotation to silence the exception and assign null value instead.
The hereby solution causes implicit eager loading of to-one relations.

If you'd like to audit properties of a superclass of an entity, which are not explicitly audited (they don't have the `@Audited` annotation on any properties or on the class),
you can set the `@AuditOverride( forClass = SomeEntity.class, isAudited = true/false )` annotation.

[NOTE]
====
The `@Audited` annotation also features an `auditParents` attribute but it's now deprecated in favor of `@AuditOverride`.
====

[[envers-audit-strategy]]
=== Choosing an audit strategy

After the basic configuration, it is important to choose the audit strategy that will be used to persist and retrieve audit information.
There is a trade-off between the performance of persisting and the performance of querying the audit information.
Currently, there are two audit strategies.

. The default audit strategy persists the audit data together with a start revision.
For each row inserted, updated or deleted in an audited table, one or more rows are inserted in the audit tables, together with the start revision of its validity.
Rows in the audit tables are never updated after insertion.
Queries of audit information use subqueries to select the applicable rows in the audit tables.
+
IMPORTANT: These subqueries are notoriously slow and difficult to index.

. The alternative is a validity audit strategy.
This strategy stores the start-revision and the end-revision of audit information.
For each row inserted, updated or deleted in an audited table, one or more rows are inserted in the audit tables, together with the start revision of its validity.
But at the same time, the end-revision field of the previous audit rows (if available) is set to this revision.
Queries on the audit information can then use 'between start and end revision' instead of subqueries as used by the default audit strategy.
+
The consequence of this strategy is that persisting audit information will be a bit slower because of the extra updates involved,
but retrieving audit information will be a lot faster.
+
IMPORTANT: This can be improved even further by adding extra indexes.

[[envers-audit-ValidityAuditStrategy]]
==== Configuring the `ValidityAuditStrategy`

To better visualize how the `ValidityAuditStrategy` works, consider the following exercise where
we replay the previous audit logging example for the `Customer` entity.

First, you need to configure the `ValidityAuditStrategy`:

[[envers-audited-validity-configuration-example]]
.Configuring the `ValidityAuditStrategy`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/ValidityStrategyAuditTest.java[tags=envers-audited-validity-configuration-example]
----
====

If, you're using the `persistence.xml` configuration file,
then the mapping will look as follows:

[source, XML, indent=0]
----
<property
    name="org.hibernate.envers.audit_strategy"
    value="org.hibernate.envers.strategy.ValidityAuditStrategy"
/>
----

Once you configured the `ValidityAuditStrategy`, the following schema is going to be automatically generated:

[[envers-audited-validity-mapping-example]]
.Envers schema for the `ValidityAuditStrategy`
====
[source, SQL, indent=0]
----
include::{extrasdir}/envers-audited-validity-mapping-example.sql[]
----
====

As you can see, the `REVEND` column is added as well as its foreign key to the `REVINFO` table.

When rerunning the previous `Customer` audit log queries against the `ValidityAuditStrategy`,
we get the following results:

[[envers-audited-validity-rev1-example]]
.Getting the first revision for the `Customer` entity
====
[source, SQL, indent=0]
----
include::{extrasdir}/envers-audited-validity-rev1-example.sql[]
----
====

[NOTE]
====
Compared to the default strategy, the `ValidityAuditStrategy` generates simpler queries that can render better SQL execution plans.
====

[[envers-revisionlog]]
=== Revision Log

When Envers starts a new revision, it creates a new revision entity which stores information about the revision.

By default, that includes just:

revision number::
An integral value (`int/Integer` or `long/Long`). Essentially, the primary key of the revision.
+
[WARNING]
====
A revision number value should **always** be increasing and never overflows.

The default implementations provided by Envers use an `int` data type which has an upper bounds of `Integer.MAX_VALUE`.
It is critical that users consider whether this upper bounds is feasible for your application.  If a large range is needed, consider using a custom revision entity mapping using a `long` data type.

In the event that the revision number reaches its upper bounds wrapping around becoming negative, an `AuditException` will be thrown causing the current transaction to be rolled back.
This guarantees that the audit history remains in a valid state that can be queried by the Envers Query API.
====

revision timestamp::
Either a `long/Long` or `java.util.Date` value representing the instant at which the revision was made.
When using a `java.util.Date`, instead of a `long/Long` for the revision timestamp, take care not to store it to a column data type which will lose precision.

Envers handles this information as an entity.
By default it uses its own internal class to act as the entity, mapped to the `REVINFO` table.
You can, however, supply your own approach to collecting this information which might be useful to capture additional details such as who made a change
or the IP address from which the request came.
There are two things you need to make this work:

. First, you will need to tell Envers about the entity you wish to use.
Your entity must use the `@org.hibernate.envers.RevisionEntity` annotation.
It must define the two attributes described above annotated with `@org.hibernate.envers.RevisionNumber` and `@org.hibernate.envers.RevisionTimestamp`, respectively.
You can extend from `org.hibernate.envers.DefaultRevisionEntity`, if you wish, to inherit all these required behaviors.
+
Simply add the custom revision entity as you do your normal entities and Envers will *find it*.
+
NOTE: It is an error for there to be multiple entities marked as `@org.hibernate.envers.RevisionEntity`.

. Second, you need to tell Envers how to create instances of your revision entity which is handled by the
https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/javadocs/org/hibernate/envers/RevisionListener.html#newRevision-java.lang.Object-[`newRevision( Object revisionEntity )`]
method of the `org.hibernate.envers.RevisionListener` interface.
+
You tell Envers your custom `org.hibernate.envers.RevisionListener` implementation to use by specifying it on the `@org.hibernate.envers.RevisionEntity` annotation, using the value attribute.
If your `RevisionListener` class is inaccessible from `@RevisionEntity` (e.g. it exists in a different module),
set `org.hibernate.envers.revision_listener` property to its fully qualified class name.
Class name defined by the configuration parameter overrides the revision entity's value attribute.

Considering we have a `CurrentUser` utility which stores the currently logged user:

[[envers-revisionlog-CurrentUser-example]]
.`CurrentUser` utility
====
[source, JAVA, indent=0]
----
include::{sourcedir}/CustomRevisionEntityTest.java[tags=envers-revisionlog-CurrentUser-example]
----
====

Now, we need to provide a custom `@RevisionEntity` to store the currently logged user

[[envers-revisionlog-RevisionEntity-example]]
.Custom `@RevisionEntity` example
====
[source, JAVA, indent=0]
----
include::{sourcedir}/CustomRevisionEntityTest.java[tags=envers-revisionlog-RevisionEntity-example]
----
====

With the custom `RevisionEntity` implementation in place,
we only need to provide the `RevisionEntity` implementation which acts as a factory
of `RevisionEntity` instances.

[[envers-revisionlog-RevisionListener-example]]
.Custom `@RevisionListener` example
====
[source, JAVA, indent=0]
----
include::{sourcedir}/CustomRevisionEntityTest.java[tags=envers-revisionlog-RevisionListener-example]
----
====

When generating the database schema, Envers creates the following `RevisionEntity` table:

[[envers-revisionlog-custom-revision-entity-table-example]]
.Auto-generated `RevisionEntity` Envers table
====
[source, SQL, indent=0]
----
include::{extrasdir}/envers-revisionlog-custom-revision-entity-table-example.sql[]
----
====

You can see the `username` column in place.

Now, when inserting a `Customer` entity, Envers generates the following statements:

[[envers-revisionlog-RevisionEntity-persist-example]]
.Auditing using the custom `@RevisionEntity` instance
====
[source, JAVA, indent=0]
----
include::{sourcedir}/CustomRevisionEntityTest.java[tags=envers-revisionlog-RevisionEntity-persist-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-revisionlog-RevisionEntity-persist-example.sql[]
----
====

As demonstrated by the example above, the username is properly set and propagated to the `CUSTOM_REV_INFO` table.

[WARNING]
====
**This strategy is deprecated since version 5.2. The alternative is to use dependency injection offered as of version 5.3.**

An alternative method to using the `org.hibernate.envers.RevisionListener` is to instead call the
[line-through]#https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/javadocs/org/hibernate/envers/AuditReader.html#getCurrentRevision-java.lang.Class-boolean-[`getCurrentRevision( Class<T> revisionEntityClass, boolean persist )`]#
method of the `org.hibernate.envers.AuditReader` interface to obtain the current revision,
and fill it with desired information.

The method accepts a `persist` parameter indicating whether the revision entity should be persisted prior to returning from this method:

`true`:: ensures that the returned entity has access to its identifier value (revision number), but the revision entity will be persisted regardless of whether there are any audited entities changed.
`false`:: means that the revision number will be `null`, but the revision entity will be persisted only if some audited entities have changed.
====

[NOTE]
====
As of Hibernate Envers 5.3, dependency injection is now supported for a `RevisionListener`.

This feature is up to the various dependency frameworks, such as CDI and Spring, to supply the
necessary implementation during Hibernate ORM bootstrap to support injection. If no qualifying
implementation is supplied, the `RevisionListener` will be constructed without injection.
====

[[envers-tracking-modified-entities-revchanges]]
=== Tracking entity names modified during revisions

By default, entity types that have been changed in each revision are not being tracked.
This implies the necessity to query all tables storing audited data in order to retrieve changes made during the specified revision.
Envers provides a simple mechanism that creates `REVCHANGES` table which stores entity names of modified persistent objects.
Single record encapsulates the revision identifier (foreign key to `REVINFO` table) and a string value.

Tracking of modified entity names can be enabled in three different ways:

. Set `org.hibernate.envers.track_entities_changed_in_revision` parameter to `true`.
  In this case `org.hibernate.envers.DefaultTrackingModifiedEntitiesRevisionEntity` will be implicitly used as the revision log entity.
. Create a custom revision entity that extends `org.hibernate.envers.DefaultTrackingModifiedEntitiesRevisionEntity` class.
+
[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditDefaultTrackingTest.java[tags=envers-tracking-modified-entities-revchanges-example]
----
+
. Mark an appropriate field of a custom revision entity with `@org.hibernate.envers.ModifiedEntityNames` annotation.
  The property is required to be of `Set<String>` type.
+
[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditTest.java[tags=envers-tracking-modified-entities-revchanges-example]
----

Considering we have a `Customer` entity illustrated by the following example:

[[envers-tracking-modified-entities-revchanges-before-rename-example]]
.`Customer` entity before renaming
====
[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditTest.java[tags=envers-tracking-modified-entities-revchanges-before-rename-example]
----
====

If the `Customer` entity class name is changed to `ApplicationCustomer`,
Envers is going to insert a new record in the `REVCHANGES` table with the previous entity class name:

[[envers-tracking-modified-entities-revchanges-after-rename-example]]
.`Customer` entity after renaming
====
[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditTest.java[tags=envers-tracking-modified-entities-revchanges-after-rename-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-tracking-modified-entities-revchanges-after-rename-example.sql[]
----
====

Users, that have chosen one of the approaches listed above,
can retrieve all entities modified in a specified revision by utilizing API described in <<envers-tracking-modified-entities-queries>>.

Users are also allowed to implement custom mechanisms of tracking modified entity types.
In this case, they shall pass their own implementation of `org.hibernate.envers.EntityTrackingRevisionListener`
interface as the value of `@org.hibernate.envers.RevisionEntity` annotation.

`EntityTrackingRevisionListener` interface exposes one method that notifies whenever audited entity instance has been
added, modified or removed within current revision boundaries.

[[envers-tracking-modified-entities-revchanges-EntityTrackingRevisionListener-example]]
.The `EntityTrackingRevisionListener` implementation
====
[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditTrackingRevisionListenerTest.java[tags=envers-tracking-modified-entities-revchanges-EntityTrackingRevisionListener-example]
----
====

The `CustomTrackingRevisionListener` adds the fully-qualified class name to the `modifiedEntityTypes` attribute of the `CustomTrackingRevisionEntity`.

[[envers-tracking-modified-entities-revchanges-RevisionEntity-example]]
.The `RevisionEntity` using the custom `EntityTrackingRevisionListener`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditTrackingRevisionListenerTest.java[tags=envers-tracking-modified-entities-revchanges-RevisionEntity-example]
----
====

The `CustomTrackingRevisionEntity` contains a `@OneToMany` list of `ModifiedTypeRevisionEntity`

[[envers-tracking-modified-entities-revchanges-EntityType-example]]
.The `EntityType` encapsulates the entity type name before a class name modification
====
[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditTrackingRevisionListenerTest.java[tags=envers-tracking-modified-entities-revchanges-EntityType-example]
----
====

Now, when fetching the `CustomTrackingRevisionEntity`, you can get access to the previous entity class name.

[[envers-tracking-modified-entities-revchanges-query-example]]
.Getting the `EntityType` through the `CustomTrackingRevisionEntity`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditTrackingRevisionListenerTest.java[tags=envers-tracking-modified-entities-revchanges-query-example]
----
====

[[envers-tracking-properties-changes]]
=== Tracking entity changes at the property level

By default, the only information stored by Envers are revisions of modified entities.
This approach lets users create audit queries based on historical values of entity properties.
Sometimes it is useful to store additional metadata for each revision, when you are interested also in the type of changes, not only about the resulting values.

The feature described in <<envers-tracking-modified-entities-revchanges>> makes it possible to tell which entities were modified in a given revision.

The feature described here takes it one step further.
_Modification Flags_ enable Envers to track which properties of audited entities were modified in a given revision.

Tracking entity changes at the property level can be enabled by:

. setting `org.hibernate.envers.global_with_modified_flag` configuration property to `true`.
  This global switch will cause adding modification flags to be stored for all audited properties of all audited entities.

. using `@Audited( withModifiedFlag = true )` on a property or on an entity.

The trade-off coming with this functionality is an increased size of audit tables and a very little, almost negligible, performance drop during audit writes.
This is due to the fact that every tracked property has to have an accompanying boolean column in the schema that stores information about the property modifications.
Of course, it is Enver's job to fill these columns accordingly - no additional work by the developer is required.
Because of costs mentioned, it is recommended to enable the feature selectively, when needed with use of the granular configuration means described above.

[[envers-tracking-properties-changes-mapping-example]]
.Mapping for tracking entity changes at the property level
====
[source, JAVA, indent=0]
----
include::{sourcedir}/ModifiedFlagsAuditTest.java[tags=envers-tracking-properties-changes-mapping-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-tracking-properties-changes-mapping-example.sql[]
----
====

As you can see, every property features a `_MOD` column (e.g. `createdOn_MOD`) in the audit log.

[[envers-tracking-properties-changes-example]]
.Tracking entity changes at the property level example
====
[source, JAVA, indent=0]
----
include::{sourcedir}/ModifiedFlagsAuditTest.java[tags=envers-tracking-properties-changes-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-tracking-properties-changes-example.sql[]
----
====

To see how "Modified Flags" can be utilized, check out the very simple query API that uses them: <<envers-tracking-properties-changes-queries>>.

[[envers-tracking-properties-changes-strategy]]
=== Selecting strategy for tracking property level changes

By default, Envers uses the `legacy` modified column naming strategy.
This strategy is designed to add columns based on the following rule-set:

. If property is annotated with `@Audited` and the _modifiedColumnName_ attribute is specified, the column will directly be based on the supplied name.
. If property is not annotated with `@Audited` or if no _modifiedColumnName_ attribute is given, the column will be named after the java class property, appended with the configured suffix, the default being `_MOD`.

While this strategy has no performance drawbacks, it does present concerns for users who prefer consistency without verbosity.
Lets take the following entity mapping as an example.

```
@Audited(withModifiedFlags = true)
@Entity
public class Customer {
  @Id
  private Integer id;
  @Column(name = "customer_name")
  private String name;
}
```

This mapping will actually lead to some inconsistent naming between columns, see below for how the model's name will be stored in `customer_name` but the modified column that tracks whether this column changes between revisions is named `name_MOD`.

```
CREATE TABLE Customer_AUD (
    id bigint not null,
    REV integer not null,
    REVTYPE tinyint not null,
    customer_name varchar(255),
    name_MOD boolean,
    primary key(id, REV)
)
```

An additional strategy called `improved`, aims to address these inconsistent column naming concerns.
This strategy uses the following rule-set:

. Property is a Basic type (Single Column valued property)
.. Use the _modifiedColumnName_ directly if one is supplied on the property mapping
.. Otherwise use the resolved ORM column name appended with the modified flag suffix configured value
. Property is an Association (to-one mapping) with a Foreign Key using a single column
.. Use the _modifiedColumnName_ directly if one is supplied on the property mapping
.. Otherwise use the resolved ORM column name appended with the modified flag suffix configured value
. Property is an Association (to-one mapping) with a Foreign Key using multiple columns
.. Use the _modifiedColumnName_ directly if one is supplied on the property mapping
.. Otherwise use the property name appended with the modified flag suffix configured value
. Property is an Embeddable
.. Use the _modifiedColumnName_ directly if one is supplied on the property mapping
.. Otherwise use the property name appended with the modified flag suffix configured value

While using this strategy, the same `Customer` mapping will generate the following table schema:

```
CREATE TABLE Customer_AUD (
    id bigint not null,
    REV integer not null,
    REVTYPE tinyint not null,
    customer_name varchar(255),
    customer_name_MOD boolean,
    primary key(id, REV)
)
```

When already using Envers in conjunction with the modified columns flag feature, it is advised not to enable the new strategy immediately as schema changes would be required.
You will need to either migrate your existing schema manually to adhere to the rules above or use the explicit _modifiedColumnName_ attribute on the `@Audited` annotation for existing columns that use the feature.

To configure a custom strategy implementation or use the improved strategy, the configuration option `org.hibernate.envers.modified_column_naming_strategy` will need to be set.
This option can be the fully qualified class name of a `ModifiedColumnNameStrategy` implementation or `legacy` or `improved` for either of the two provided implementations.

[[envers-queries]]
=== Queries

You can think of historic data as having two dimensions:

horizontal:: The state of the database at a given revision. Thus, you can query for entities as they were at revision N.
vertical:: The revisions, at which entities changed. Hence, you can query for revisions, in which a given entity changed.

The queries in Envers are similar to Hibernate Criteria queries, so if you are familiar with them, using Envers queries will be much easier.

The main limitation of the current queries implementation is that you cannot traverse relations.
You can only specify constraints on the ids of the related entities, and only on the "owning" side of the relation.
This, however, will be changed in future releases.

[NOTE]
====
The queries on the audited data will be in many cases much slower than corresponding queries on "live" data,
as, especially for the default audit strategy, they involve correlated subselects.

Queries are improved both in terms of speed and possibilities when using the validity audit strategy,
which stores both start and end revisions for entities. See <<envers-audit-ValidityAuditStrategy>> for a more detailed discussion.
====

[[entities-at-revision]]
=== Querying for entities of a class at a given revision

The entry point for this type of queries is:

[[entities-at-revision-example]]
.Getting the `Customer` entity at a given revision
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=entities-at-revision-example]
----
====

[[entities-filtering]]
=== Querying for entities using filtering criteria

You can then specify constraints, which should be met by the entities returned, by adding restrictions,
which can be obtained using the `AuditEntity` factory class.

For example, to select only entities where the `firstName` property is equal to "John":

[[entities-filtering-example]]
.Getting the `Customer` audit log with a given `firstName` attribute value
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=entities-filtering-example]
----
====

And, to select only entities whose relationships are related to a given entity,
you can use either the target entity or its identifier.

[[entities-filtering-by-entity-example]]
.Getting the `Customer` entities whose `address` attribute matches the given entity reference
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=entities-filtering-by-entity-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/entities-filtering-by-entity-example.sql[]
----
====

The same SQL is generated even if we provide the identifier instead of the target entity reference.

[[entities-filtering-by-entity-identifier-example]]
.Getting the `Customer` entities whose `address` identifier matches the given entity identifier
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=entities-filtering-by-entity-identifier-example]
----
====

Apart from strict equality matching, you can also use an `IN` clause to provide multiple entity identifiers:

[[entities-in-clause-filtering-by-entity-identifier-example]]
.Getting the `Customer` entities whose `address` identifier matches one of the given entity identifiers
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=entities-in-clause-filtering-by-entity-identifier-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/entities-in-clause-filtering-by-entity-identifier-example.sql[]
----
====

You can limit the number of results, order them, and set aggregations and projections (except grouping) in the usual way.
When your query is complete, you can obtain the results by calling the `getSingleResult()` or `getResultList()` methods.

A full query, can look for example like this:

[[entities-filtering-and-pagination]]
.Getting the `Customer` entities using filtering and pagination
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=entities-filtering-and-pagination]
----

[source, SQL, indent=0]
----
include::{extrasdir}/entities-filtering-and-pagination.sql[]
----
====

[[revisions-of-entity]]
=== Querying for revisions, at which entities of a given class changed

The entry point for this type of queries is:

[[revisions-of-entity-query-example]]
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=revisions-of-entity-query-example]
----

You can add constraints to this query in the same way as to the previous one.

There are some additional possibilities:

. using `AuditEntity.revisionNumber()` you can specify constraints, projections and order on the revision number, in which the audited entity was modified.

. similarly, using `AuditEntity.revisionProperty( propertyName )` you can specify constraints, projections and order on a property of the revision entity,
  corresponding to the revision in which the audited entity was modified.

. `AuditEntity.revisionType()` gives you access as above to the type of the revision (`ADD`, `MOD`, `DEL`).

Using these methods, you can order the query results by revision number, set projection or constraint the revision number to be greater or less than a specified value, etc.
For example, the following query will select the smallest revision number, at which entity of class `MyEntity` with id `entityId` has changed, after revision number 2:

[[revisions-of-entity-query-by-revision-number-example]]
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=revisions-of-entity-query-by-revision-number-example]
----

The second additional feature you can use in queries for revisions is the ability to _maximize_/_minimize_ a property.

For example, if you want to select the smallest possible revision at which the value of the `createdOn`
attribute was larger then a given value,
you can run the following query:

[[revisions-of-entity-query-minimize-example]]
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=revisions-of-entity-query-minimize-example]
----

The `minimize()` and `maximize()` methods return a criterion, to which you can add constraints,
which must be met by the entities with the _maximized_/_minimized_ properties.

You probably also noticed that there are two boolean parameters, passed when creating the query.

`selectEntitiesOnly`:: The first parameter is only valid when you don't set an explicit projection.
+
If true, the result of the query will be a list of entities (which changed at revisions satisfying the specified constraints).
+
If false, the result will be a list of three element arrays:

* the first element will be the changed entity instance.
* the second will be an entity containing revision data (if no custom entity is used, this will be an instance of `DefaultRevisionEntity`).
* the third will be the type of the revision (one of the values of the `RevisionType` enumeration: `ADD`, `MOD`, `DEL`).

`selectDeletedEntities`:: The second parameter specifies if revisions,
in which the entity was deleted should be included in the results.
+
If yes, such entities will have the revision type `DEL` and all attributes, except the `id`, will be set to `null`.

Another useful feature is `AggregatedAuditExpression#computeAggregationInInstanceContext()`.  This can be used to create
an aggregate query based on the entity instance primary key.

For example, if you wanted to locate all customers but only wanted to retrieve the instances with the
maximum revision number, you would use the following query:

[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=aggregate-max-revision-with-entity-example]
----

In other words, the result set would contain a list of `Customer` instances, one per primary key.  Each instance would
hold the audited property data at the _maximum_ revision number for each `Customer` primary key.

[[envers-tracking-properties-changes-queries]]
=== Querying for entity revisions that modified a given property

For the two types of queries described above it's possible to use special `Audit` criteria called `hasChanged()` and `hasNotChanged()`
that make use of the functionality described in <<envers-tracking-properties-changes>>.

Let's have a look at various queries that can benefit from these two criteria.

First, you must make sure that your entity can track _modification flags_:

[[envers-tracking-properties-changes-queries-entity-example]]
.Valid only when audit logging tracks entity attribute modification flags
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditWithModifiedFlagTest.java[tags=envers-tracking-properties-changes-queries-entity-example]
----
====

The following query will return all revisions of the `Customer` entity with the given `id`,
for which the `lastName` property has changed.

[[envers-tracking-properties-changes-queries-hasChanged-example]]
.Getting all `Customer` revisions for which the `lastName` attribute has changed
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditWithModifiedFlagTest.java[tags=envers-tracking-properties-changes-queries-hasChanged-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-tracking-properties-changes-queries-hasChanged-example.sql[]
----
====

Using this query we won't get all other revisions in which `lastName` wasn't touched.
From the SQL query you can see that the `lastName_MOD` column is being used in the WHERE clause,
hence the aforementioned requirement for tracking modification flags.

Of course, nothing prevents users from combining `hasChanged` condition with some additional criteria.

[[envers-tracking-properties-changes-queries-hasChanged-and-hasNotChanged-example]]
.Getting all `Customer` revisions for which the `lastName` attribute has changed and the `firstName` attribute has not changed
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditWithModifiedFlagTest.java[tags=envers-tracking-properties-changes-queries-hasChanged-and-hasNotChanged-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-tracking-properties-changes-queries-hasChanged-and-hasNotChanged-example.sql[]
----
====

To get the `Customer` entities changed at a given `revisionNumber` with `lastName` modified and `firstName` untouched,
we have to use the `forEntitiesModifiedAtRevision` query:

[[envers-tracking-properties-changes-queries-at-revision-example]]
.Getting the `Customer` entity for a given revision if the `lastName` attribute has changed and the `firstName` attribute has not changed
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditWithModifiedFlagTest.java[tags=envers-tracking-properties-changes-queries-at-revision-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-tracking-properties-changes-queries-at-revision-example.sql[]
----
====

[[envers-tracking-obtain-properties-changed-queries]]
=== Querying for revisions of entity including property names that were modified

[NOTE]
====
This feature described here is still considered experimental.
It is subject to change in future releases based on user feedback to improve its usefulness.
====

Sometimes it may be useful to query entity revisions and also determine all the properties of that revision which
were modified without having to issue multiple queries using `hasChanged()` and `hasNotChanged()` criteria.

You can now obtain this information easily by using the following query:

.Querying entity revisions including property names modified.
====
[source, JAVA, indent=0]
----
List results  = AuditReaderFactory.get( entityManager )
    .createQuery()
    .forRevisionsOfEntityWithChanges( Customer.class, false )
    .add( AuditEntity.id().eq( 1L ) )
    .getResultList();

for ( Object entry : results ) {
    final Object[] array = (Object[]) entry;
    final Set<String> propertiesChanged = (Set<String>) array[3];
    for ( String propertyName : propertiesChanged ) {
    /* Do something useful with the modified property `propertyName` */
    }
}
----
====

[[envers-tracking-modified-entities-queries]]
=== Querying for entity types modified in a given revision

[NOTE]
====
The methods described below can be used only when the default mechanism of tracking changed entity types is enabled (see <<envers-tracking-modified-entities-revchanges>>).
====

This basic query allows retrieving entity names and corresponding Java classes changed in a specified revision:

[[envers-tracking-modified-entities-queries-example]]
.Retrieving entity names and corresponding Java classes changed in a specified revision
====
[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditTest.java[tags=envers-tracking-modified-entities-queries-example1]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/EntityTypeChangeAuditTest.java[tags=envers-tracking-modified-entities-queries-example2]
----
====

Other queries (also accessible from `org.hibernate.envers.CrossTypeRevisionChangesReader`):

`List<Object> findEntities(Number)`::
  Returns snapshots of all audited entities changed (added, updated and removed) in a given revision.
  Executes `N + 1` SQL queries, where `N` is a number of different entity classes modified within specified revision.

`List<Object> findEntities(Number, RevisionType)`::
  Returns snapshots of all audited entities changed (added, updated or removed) in a given revision filtered by modification type.
  Executes `N + 1` SQL queries, where `N` is a number of different entity classes modified within specified revision.

`Map<RevisionType, List<Object>> findEntitiesGroupByRevisionType(Number)`::
  Returns a map containing lists of entity snapshots grouped by modification operation (e.g. addition, update and removal).
  Executes `3N + 1` SQL queries, where `N` is a number of different entity classes modified within specified revision.

[[envers-querying-entity-relation-joins]]
=== Querying for entities using entity relation joins

[WARNING]
====
Relation join queries are considered experimental and may change in future releases.
====

Audit queries support the ability to apply constraints, projections, and sort operations based on entity relations.  In order
to traverse entity relations through an audit query, you must use the relation traversal API with a join type.

[NOTE]
====
Relation joins can be applied to `many-to-one` and `one-to-one` mappings only when using `JoinType.LEFT` or `JoinType.INNER`.
====

The basis for creating an entity relation join query is as follows:

[[envers-querying-entity-relation-inner-join]]
.INNER JOIN entity audit query
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=envers-querying-entity-relation-inner-join]
----
====

[[envers-querying-entity-relation-left-join]]
.LEFT JOIN entity audit query
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=envers-querying-entity-relation-left-join]
----
====

Like any other query, constraints may be added to restrict the results.

For example, to find all `Customer` entities at a given revision whose addresses are in `România`,
you can use the following query:

[[envers-querying-entity-relation-join-restriction]]
.Filtering the join relation with a WHERE clause predicate
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditTest.java[tags=envers-querying-entity-relation-join-restriction]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-querying-entity-relation-join-restriction.sql[]
----
====

It is also possible to traverse beyond the first relation in an entity graph.

For example, to find all `Customer` entities at a given revision
with the country attribute of the address property being `România`:

[[envers-querying-entity-relation-nested-join-restriction]]
.Filtering a nested join relation with a WHERE clause predicate
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditAdressCountryTest.java[tags=envers-querying-entity-relation-nested-join-restriction]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-querying-entity-relation-nested-join-restriction.sql[]
----
====

Constraints may also be added to the properties of nested joined relations, such as testing for `null`.

For example, the following query illustrates how to find all `Customer` entities at a given revision
having the `address` in `Cluj-Napoca` or the `address` does _not_ have any country entity reference:

[[envers-querying-entity-relation-join-multiple-restrictions]]
.Filtering a join relation using multiple predicates
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditAdressCountryTest.java[tags=envers-querying-entity-relation-join-multiple-restrictions]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-querying-entity-relation-join-multiple-restrictions.sql[]
----
====

[NOTE]
====
Queries can use the `up` method to navigate back up the entity graph.
====

Disjunction criterion may also be applied to relation join queries.

For example, the following query will find all `Customer` entities at a given revision
where the country name is `România` or that the `Customer` lives in `Cluj-Napoca`:

[[envers-querying-entity-relation-nested-join-multiple-restrictions]]
.Filtering a nested join relation using multiple predicates
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditAdressCountryTest.java[tags=envers-querying-entity-relation-nested-join-multiple-restrictions]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-querying-entity-relation-nested-join-multiple-restrictions.sql[]
----
====

Lastly, this example illustrates how related entity properties can be compared in a single constraint.

Assuming the `Customer` and the `Address` were previously changed as follows:

[[envers-querying-entity-relation-nested-join-multiple-restrictions-combined-entities]]
.Changing the `Address` to match the `Country` name
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditAdressCountryTest.java[tags=envers-querying-entity-relation-nested-join-multiple-restrictions-combined-entities]
----
====

The following query shows how to find the `Customer` entities
where the `city` property of the `address` attribute equals the `name` of the associated `country` attribute.

[[envers-querying-entity-relation-nested-join-multiple-restrictions-combined]]
.Filtering a nested join relation using multiple predicates
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditAdressCountryTest.java[tags=envers-querying-entity-relation-nested-join-multiple-restrictions-combined]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-querying-entity-relation-nested-join-multiple-restrictions-combined.sql[]
----
====

[[envers-querying-revision-entities]]
=== Querying for revision information without loading entities

Sometimes, it may be useful to load information about revisions to find out who performed specific revisions or
to know what entity names were modified but the change log about the related audited entities isn't needed.
This API allows an efficient way to get the revision information entity log without instantiating the actual
entities themselves.

Here is a simple example:

[source,java]
----
AuditQuery query = getAuditReader().createQuery()
    .forRevisionsOfEntity( DefaultRevisionEntity.class, true )
    .add( AuditEntity.revisionNumber().between( 1, 25 ) );
----

This query will return all revision information entities for revisions between 1 and 25 including those which are
related to deletions.  If deletions are not of interest, you would pass `false` as the second argument.

Note that this query uses the `DefaultRevisionEntity` class type.  The class provided will vary depending on the
configuration properties used to configure Envers or if you supply your own revision entity.  Typically users who
will use this API will likely be providing a custom revision entity implementation to obtain custom information
being maintained per revision.

[[envers-conditional-auditing]]
=== Conditional auditing

Envers persists audit data in reaction to various Hibernate events (e.g. `post update`, `post insert`, and so on),
using a series of event listeners from the `org.hibernate.envers.event.spi` package.
By default, if the Envers jar is in the classpath, the event listeners are auto-registered with Hibernate.

Conditional auditing can be implemented by overriding some of the Envers event listeners.
To use customized Envers event listeners, the following steps are needed:

. Turn off automatic Envers event listeners registration by setting the `hibernate.envers.autoRegisterListeners` Hibernate property to `false`.

. Create subclasses for appropriate event listeners.
  For example, if you want to conditionally audit entity insertions, extend the `org.hibernate.envers.event.spi.EnversPostInsertEventListenerImpl` class.
  Place the conditional-auditing logic in the subclasses, call the super method if auditing should be performed.

. Create your own implementation of `org.hibernate.integrator.spi.Integrator`, similar to `org.hibernate.envers.boot.internal.EnversIntegrator`.
  Use your event listener classes instead of the default ones.

. For the integrator to be automatically used when Hibernate starts up, you will need to add a `META-INF/services/org.hibernate.integrator.spi.Integrator` file to your jar.
  The file should contain the fully qualified name of the class implementing the interface.

[NOTE]
====
The use of `hibernate.listeners.envers.autoRegister` has been deprecated.
The new `hibernate.envers.autoRegisterListeners` configuration setting should be used instead.
====

[[envers-schema]]
=== Understanding the Envers Schema

For each audited entity (that is, for each entity containing at least one audited field), an audit table is created.
By default, the audit table's name is created by adding an "_AUD" suffix to the original table name,
but this can be overridden by specifying a different suffix/prefix in the configuration properties or per-entity using the `@org.hibernate.envers.AuditTable` annotation.

The audit table contains the following columns:

id:: `id` of the original entity (this can be more then one column in the case of composite primary keys).
revision number:: an integer, which matches to the revision number in the revision entity table.
revision type:: The `org.hibernate.envers.RevisionType` enumeration ordinal stating if the change represents an INSERT, UPDATE or DELETE.
audited fields:: properties from the original entity being audited.

The primary key of the audit table is the combination of the original id of the entity and the revision number,
so there can be at most one historic entry for a given entity instance at a given revision.

The current entity data is stored in the original table and in the audit table.
This is a duplication of data, however, as this solution makes the query system much more powerful, and as memory is cheap, hopefully, this won't be a major drawback for the users.

A row in the audit table with entity id `ID`, revision `N`, and data `D` means: entity with id `ID` has data `D` from revision `N` upwards.
Hence, if we want to find an entity at revision `M`, we have to search for a row in the audit table, which has the revision number smaller or equal to `M`, but as large as possible.
If no such row is found, or a row with a "deleted" marker is found, it means that the entity didn't exist at that revision.

The "revision type" field can currently have three values: `0`, `1` and `2`, which means `ADD`, `MOD`, and `DEL`, respectively.
A row with a revision of type `DEL` will only contain the id of the entity and no data (all fields `NULL`), as it only serves as a marker saying "this entity was deleted at that revision".

Additionally, there is a revision entity table which contains the information about the global revision.
By default, the generated table is named `REVINFO` and contains just two columns: `ID` and `TIMESTAMP`.
A row is inserted into this table on each new revision, that is, on each commit of a transaction, which changes audited data.
The name of this table can be configured, the name of its columns as well as adding additional columns can be achieved as discussed in <<envers-revisionlog>>.

[NOTE]
====
While global revisions are a good way to provide correct auditing of relations, some people have pointed out that this may be a bottleneck in systems where data is very often modified.

One viable solution is to introduce an option to have an entity "locally revisioned", that is revisions would be created for it independently.
This would not enable correct versioning of relations, but it would work without the `REVINFO` table.

Another possibility is to introduce a notion of "revisioning groups", which would group entities sharing the same revision numbering.
Each such group would have to consist of one or more strongly connected components belonging to the entity graph induced by relations between entities.

Your opinions on the subject are very welcome on the forum.
====

[[envers-generateschema]]
=== Generating Envers schema with Hibernate hbm2ddl tool

If you would like to generate the database schema file with Hibernate,
you simply need to use the hbm2ddl too.

This task will generate the definitions of all entities, both of those which are audited by Envers and those which are not.

See the <<chapters/schema/Schema.adoc#schema-generation, Schema generation>> chapter for more info.

For the following entities, Hibernate is going to generate the following database schema:

[[envers-generateschema-example]]
.Filtering a nested join relation using multiple predicates
====
[source, JAVA, indent=0]
----
include::{sourcedir}/QueryAuditAdressCountryTest.java[tags=envers-generateschema-example]
----

[source, SQL, indent=0]
----
include::{extrasdir}/envers-generateschema-example.sql[]
----
====

[[envers-mappingexceptions]]
=== Mapping exceptions

==== What isn't and will not be supported

Bags are not supported because they can contain non-unique elements.
Persisting a bag of `String`s violates the relational database principle that each table is a set of tuples.

In case of bags, however (which require a join table), if there is a duplicate element, the two tuples corresponding to the elements will be the same.
Although Hibernate allows this, Envers (or more precisely the database connector) will throw an exception when trying to persist two identical elements because of a unique constraint violation.

There are at least two ways out if you need bag semantics:

. use an indexed collection, with the `@javax.persistence.OrderColumn` annotation.
. provide a unique id for your elements with the `@CollectionId` annotation.

==== What isn't and _will_ be supported

* Bag style collections with a `@CollectionId` identifier column (see https://hibernate.atlassian.net/browse/HHH-3950[HHH-3950]).

=== `@OneToMany` with `@JoinColumn`

When a collection is mapped using these two annotations, Hibernate doesn't generate a join table.
Envers, however, has to do this so that when you read the revisions in which the related entity has changed, you don't get false results.

To be able to name the additional join table, there is a special annotation: `@AuditJoinTable`, which has similar semantics to JPA `@JoinTable`.

One special case is to have relations mapped with `@OneToMany` with `@JoinColumn` on the one side, and `@ManyToOne` and `@JoinColumn( insertable = false, updatable = false`) on the many side.
Such relations are, in fact, bidirectional, but the owning side is the collection.

To properly audit such relations with Envers, you can use the `@AuditMappedBy` annotation.
It enables you to specify the reverse property (using the `mappedBy` element).
In case of indexed collections, the index column must also be mapped in the referenced entity (using `@Column( insertable = false, updatable = false )`, and specified using `positionMappedBy`.
This annotation will affect only the way Envers works.
Please note that the annotation is experimental and may change in the future.

[[envers-partitioning]]
=== Advanced: Audit table partitioning

[[envers-partitioning-benefits]]
=== Benefits of audit table partitioning

Because audit tables tend to grow indefinitely, they can quickly become really large.
When the audit tables have grown to a certain limit (varying per RDBMS and/or operating system) it makes sense to start using table partitioning.
SQL table partitioning offers a lot of advantages including, but certainly not limited to:

. Improved query performance by selectively moving rows to various partitions (or even purging old rows).
. Faster data loads, index creation, etc.

[[envers-partitioning-columns]]
=== Suitable columns for audit table partitioning

Generally, SQL tables must be partitioned on a column that exists within the table.
As a rule, it makes sense to use either the _end revision_ or the _end revision timestamp_ column for partitioning of audit tables.

[NOTE]
====
End revision information is not available for the default `AuditStrategy`.

Therefore the following Envers configuration options are required:

`org.hibernate.envers.audit_strategy` = `org.hibernate.envers.strategy.ValidityAuditStrategy`

`org.hibernate.envers.audit_strategy_validity_store_revend_timestamp` = `true`

Optionally, you can also override the default values using following properties:

`org.hibernate.envers.audit_strategy_validity_end_rev_field_name`

`org.hibernate.envers.audit_strategy_validity_revend_timestamp_field_name`

For more information, see <<envers-configuration>>.
====

The reason why the end revision information should be used for audit table partitioning is based on the assumption that audit tables should be partitioned on an 'increasing level of relevancy', like so:

. A couple of partitions with audit data that is not very (or no longer) relevant.
  This can be stored on slow media, and perhaps even be purged eventually.
. Some partitions for audit data that is potentially relevant.
. One partition for audit data that is most likely to be relevant.
  This should be stored on the fastest media, both for reading and writing.

[[envers-partitioning-example]]
=== Audit table partitioning example

In order to determine a suitable column for the 'increasing level of relevancy',
consider a simplified example of a salary registration for an unnamed agency.

Currently, the salary table contains the following rows for a certain person X:

.Salaries table
[width="100%",cols="50%,50%",options="header",]
|==================
|Year |Salary (USD)
|2006 |3300
|2007 |3500
|2008 |4000
|2009 |4500
|==================

The salary for the current fiscal year (2010) is unknown.
The agency requires that all changes in registered salaries for a fiscal year are recorded (i.e., an audit trail).
The rationale behind this is that decisions made at a certain date are based on the registered salary at that time.
And at any time it must be possible to reproduce the reason why a certain decision was made at a certain date.

The following audit information is available, sorted in order of occurrence:

.Salaries - audit table
[width="100%",cols="20%,20%,20%,20%,20%",options="header",]
|=======================================================================
|Year |Revision type |Revision timestamp |Salary (USD) |End revision timestamp
|2006 |ADD 			 |2007-04-01         |3300         |null
|2007 |ADD           |2008-04-01         |35           |2008-04-02
|2007 |MOD           |2008-04-02         |3500         |null
|2008 |ADD           |2009-04-01         |3700         |2009-07-01
|2008 |MOD           |2009-07-01         |4100         |2010-02-01
|2008 |MOD           |2010-02-01         |4000         |null
|2009 |ADD           |2010-04-01         |4500         |null
|=======================================================================

[[envers-partitioning-example-column]]
=== Determining a suitable partitioning column

To partition this data, the _level of relevancy_ must be defined. Consider the following:

. For the fiscal year 2006, there is only one revision.
It has the oldest _revision timestamp_ of all audit rows,
but should still be regarded as relevant because it's the latest modification for this fiscal year in the salary table (its _end revision timestamp_ is null).
+
Also, note that it would be very unfortunate if in 2011 there would be an update of the salary for the fiscal year 2006 (which is possible until at least 10 years after the fiscal year),
and the audit information would have been moved to a slow disk (based on the age of the __revision timestamp__).
Remember that, in this case, Envers will have to update the _end revision timestamp_ of the most recent audit row.
. There are two revisions in the salary of the fiscal year 2007 which both have nearly the same _revision timestamp_ and a different __end revision timestamp__.

On first sight, it is evident that the first revision was a mistake and probably not relevant.
The only relevant revision for 2007 is the one with _end revision timestamp_ value of null.

Based on the above, it is evident that only the _end revision timestamp_ is suitable for audit table partitioning.
The _revision timestamp_ is not suitable.

[[envers-partitioning-example-scheme]]
=== Determining a suitable partitioning scheme

A possible partitioning scheme for the salary table would be as follows:

_end revision timestamp_ year = 2008:: This partition contains audit data that is not very (or no longer) relevant.
_end revision timestamp_ year = 2009:: This partition contains audit data that is potentially relevant.
_end revision timestamp_ year >= 2010 or null:: This partition contains the most relevant audit data.

This partitioning scheme also covers the potential problem of the update of the __end revision timestamp__,
which occurs if a row in the audited table is modified.
Even though Envers will update the _end revision timestamp_ of the audit row to the system date at the instant of modification,
the audit row will remain in the same partition (the 'extension bucket').

And sometime in 2011, the last partition (or 'extension bucket') is split into two new partitions:

. _end revision timestamp_ year = 2010: This partition contains audit data that is potentially relevant (in 2011).
. _end revision timestamp_ year >= 2011 or null: This partition contains the most interesting audit data and is the new 'extension bucket'.

[[envers-links]]
=== Envers links

.  http://hibernate.org[Hibernate main page]
.  http://hibernate.org/community/[Forum]
.  https://hibernate.atlassian.net/[JIRA issue tracker] (when adding issues concerning Envers, be sure to select the "envers" component!)
.  https://hibernate.zulipchat.com/#narrow/stream/132096-hibernate-user[Zulip channel]
.  https://community.jboss.org/wiki/EnversFAQ[FAQ]

