2. JPA Schema Generation

JPA 2.1 introduced a standard for database schema generation. Therefore, starting with this release we can control how to generate and export our database schema through a set of predefined configuration properties.

In essence, the script targetdefines the location of the file that contains the schema create or drop commands. So, for instance, if we choose drop-and-create as script action we'll need to specify both targets.

2.3. The Schema Source

Finally, to generate the schema DDL commands from our entity models we should include the schema source configurations with the metadata option selected:

3.2. Spring Data JPA Configuration

Now to generate the database schema we'll need to pass the schema generation properties to the persistence provider in use. To do this, we'll set the native JPA properties in our configuration file under the spring.jpa.properties prefix:

Consequently, Spring Data JPA passes these properties to the persistence provider, when it creates the EntityManagerFactory bean.

3.3. The create.sql File

As a result, on the application startup, the above configuration will generate the database creation commands based on the entity mapping metadata. Furthermore, the DDL commands are exported into the create.sql file, which is created in our main project folder:

4. Schema Generation with the Hibernate API

If we're using Hibernate, we can use directly its native API, SchemaExport, to generate our schema DDL commands. Likewise, the Hibernate API uses our application entity models to generate and export the database schema.

With Hibernate's SchemaExport we can use the drop, createOnly, and create methods explicitly:

5. Schema Generation Options

Even though schema generation can save us time during development, we should use it only for basic scenarios.

For instance, we could use it to quickly spin up development or testing databases.

In contrast, for more complex scenarios, like database migration, we should use more refined tooling like Liquibase or Flyway.

6. Conclusion

In this tutorial, we saw how to generate and export our database schema with the help of the JPA schema-generation properties. Subsequently, we saw how to achieve the same result using Hibernate's native API, SchemaExport.