[[dynamic-model]]
=== Dynamic Model
:sourcedir: ../../../../../test/java/org/hibernate/userguide/mapping/dynamic
:mappingdir: ../../../../../test/resources/org/hibernate/userguide/mapping/dynamic
:extrasdir: extras

[IMPORTANT]
====
JPA only acknowledges the entity model mapping so, if you are concerned about JPA provider portability, it's best to stick to the strict POJO model.
On the other hand, Hibernate can work with both POJO entities and dynamic entity models.
====

[[mapping-model-dynamic]]
==== Dynamic mapping models

Persistent entities do not necessarily have to be represented as POJO/JavaBean classes.
Hibernate also supports dynamic models (using `Map` of ``Map``s at runtime).
With this approach, you do not write persistent classes, only mapping files.

A given entity has just one entity mode within a given SessionFactory.
This is a change from previous versions which allowed to define multiple entity modes for an entity and to select which to load.
Entity modes can now be mixed within a domain model; a dynamic entity might reference a POJO entity and vice versa.

[[mapping-model-dynamic-example]]
.Dynamic domain model Hibernate mapping
====
[source,xml]
----
include::{mappingdir}/Book.hbm.xml[tag=mapping-model-dynamic-example, indent=0]
----
====

After you defined your entity mapping, you need to instruct Hibernate to use the dynamic mapping mode:

[[mapping-model-dynamic-setting-example]]
.Dynamic domain model Hibernate mapping
====
[source,java]
----
include::{sourcedir}/DynamicEntityTest.java[tag=mapping-model-dynamic-setting-example, indent=0]
----
====

When you are going to save the following `Book` dynamic entity,
Hibernate is going to generate the following SQL statement:

[[mapping-model-dynamic-persist-example]]
.Persist dynamic entity
====
[source,java]
----
include::{sourcedir}/DynamicEntityTest.java[tag=mapping-model-dynamic-example, indent=0]
----

[source,sql]
----
include::{extrasdir}/dynamic/mapping-model-dynamic-example.sql[indent=0]
----
====

[NOTE]
====
The main advantage of dynamic models is the quick turnaround time for prototyping without the need for entity class implementation.
The main downfall is that you lose compile-time type checking and will likely deal with many exceptions at runtime.
However, as a result of the Hibernate mapping, the database schema can easily be normalized and sound, allowing to add a proper domain model implementation on top later on.

It is also interesting to note that dynamic models are great for certain integration use cases as well.
Envers, for example, makes extensive use of dynamic models to represent the historical data.
====