Pages

Monday, February 10, 2014

Generating Schema with JPA/Hibernate

When creating new projects I tend to create the application code first and generate the database schema from that code. One of the nicer things added in JPA 2.1, which has been supported in Hibernate for several years, is the ability to generate a schema based on Java annotated classes. In practice I've found that in order to accomplish generating the schema and using it to test with an in memory database requires both Hibernate and JPA properties.

These properties will generate a script called schema.sql that will create the schema for an HSQL database. It will also load that schema with data from a file called data.sql. Note that data.sql needs to be on the classpath.

    jpaProperties.put(Environment.HBM2DDL_AUTO, "create");
    jpaProperties.put(Environment.HBM2DDL_IMPORT_FILES, "data.sql");
    jpaProperties.put("javax.persistence.schema-generation.create-database-schemas", "true");
    jpaProperties.put("javax.persistence.schema-generation.scripts.action", "create");
    jpaProperties.put("javax.persistence.schema-generation.scripts.create-target",
        "src/test/resources/schema.sql");
    jpaProperties.put("javax.persistence.database-product-name", "HSQL");

 See the complete Java configuration on github here. It uses Spring framework, Spring-data-jpa, and Hibernate.

No comments:

Post a Comment