Test-driven software must often drop, create and populate database tables with records before it runs a suite of unit tests. For this reason, the ability to have JPA frameworks -- such as EclipseLink or Hibernate -- create tables and databases as they bootstrap is built right into the specification.
These database creation facilities are also a great way to validate a newly set up Hibernate and JPA development environment. If a data-driven application can link to the underlying JPA framework, and that framework can then connect to the database and can create the underlying tables, then it is confirmed that a successful end-to-end integration has occurred.
The three most common ways to have JPA and Hibernate create tables in a database are:
- Set the xml file's database action property to drop-and-create;
- Set thecfg.xml hbm2ddl.auto property to create; or
- Run the execute method of the Hibernate SchemaExport
1. JPA database table creation
JPA is the Java ORM standard, and the secret to most JPA configurations is the persistence.xml file. A developer can simply add the database.action property to the xml and set it to one of the following four values to have JPA create tables:
The full name of the JPA table generation property is:
A developer can specify a special script for table generation or deletion with one of the following two properties:
Also, the framework can load records after table creation by providing the name of a script as a value for the following property:
2. Create database tables with Hibernate
Hibernate applications do not use a persistence.xml file, but they do have a corollary hibernate configuration file named hibernate.cfg.xml. A developer can have Hibernate create tables by adding the hbm2ddl.auto property and setting it to one of the following four values:
3. Create tables with the Hibernate SchemaExport class
A developer should avoid polluting configuration files with potentially dangerous database table drop and create options. As an alternative, it's possible to use the Hibernate SchemaExport class to programmatically create tables.
The Hibernate SchemaExport class is created the exact same way as a Hibernate SessionFactory, with properties set in a Hashtable or HashMap, a ServiceRegistry object instantiated and Java entities loaded into the MetadataSources class. After initialization, the SchemaExport class is passed an Action enum, which can be assigned one of four values:
As the SchemaExport's execute method runs, the Hibernate API creates database tables based on the entities added to the MetadataSources object.
The Hibernate 5 SchemaExport class is quite a bit different than earlier versions. The Hibernate 5 SchemaExport example shown here isn't compatible with earlier versions of the JPA framework.
The source code for each of these JPA and Hibernate create table scripts can be found on GitHub.