[[schema-generation]]
== Schema generation
:sourcedir: ../../../../../test/java/org/hibernate/userguide/schema
:extrasdir: extras
:resourcesdir: ../../../../../test/resources


Hibernate allows you to generate the database from the entity mappings.

[TIP]
====
Although the automatic schema generation is very useful for testing and prototyping purposes, in a production environment,
it's much more flexible to manage the schema using incremental migration scripts.
====

Traditionally, the process of generating  schema from entity mapping has been called `HBM2DDL`.
To get a list of Hibernate-native and JPA-specific configuration properties consider reading the <<appendices/Configurations.adoc#configurations-hbmddl,Configurations>> section.

Considering the following Domain Model:

[[schema-generation-domain-model-example]]
.Schema generation Domain Model
====
[source, JAVA, indent=0]
----
include::{sourcedir}/SchemaGenerationTest.java[tags=schema-generation-domain-model-example]
----
====

If the `hibernate.hbm2ddl.auto` configuration is set to `create`, Hibernate is going to generate the following database schema:

[[sql-schema-generation-domain-model-example]]
.Auto-generated database schema
====
[source, SQL, indent=0]
----
include::{extrasdir}/sql-schema-generation-domain-model-example.sql[]
----
====

=== Importing script files

To customize the schema generation process, the `hibernate.hbm2ddl.import_files` configuration property must be used to provide other scripts files that Hibernate can use when the `SessionFactory` is started.

For instance, considering the following `schema-generation.sql` import file:

[[schema-generation-import-file-example]]
.Schema generation import file
====
[source, JAVA, indent=0]
----
include::{resourcesdir}/schema-generation.sql[]
----
====

If we configure Hibernate to import the script above:

[[schema-generation-import-file-configuration-example]]
.Enabling query cache
====
[source, XML, indent=0]
----
<property
    name="hibernate.hbm2ddl.import_files"
    value="schema-generation.sql" />
----
====

Hibernate is going to execute the script file after the schema is automatically generated.

=== Database objects

Hibernate allows you to customize the schema generation process via the HBM `database-object` element.

Considering the following HBM mapping:

[[schema-generation-database-object-example]]
.Schema generation HBM database-object
====
[source, JAVA, indent=0]
----
include::{sourcedir}/SchemaGenerationTest.hbm.xml[]
----
====

When the `SessionFactory` is bootstrapped, Hibernate is going to execute the `database-object`, therefore creating the `sp_count_books` funtion.

