Search code examples
jpah2openjpapersistence.xml

How to create H2 table before adding records in JPA


My project involves JPA and following in my persistence.xml file

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="rest-jpa">
        <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
        <jta-data-source>java:/comp/env/jdbc/restDB</jta-data-source>
        <class>org.wso2.as.ee.Student</class>
        <properties>
            <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
        </properties>
    </persistence-unit>
</persistence>

My H2 database is a in memory database.

It gives an error of table not found when I try to find for a record before adding one. I think that the table is created only when I add a record to the database. How can I create the table before any record is added?


Solution

  • You can make use of following JPA properties:

    Generates and executes DROP TABLE and CREATE TABLE scripts everytime you run the application:

    • javax.persistence.schema-generation.database.action=drop-and-create

    Loads some predefined data after creating database:

    • javax.persistence.sql-load-script-source="META-INF/loadData.ddl"

    Creating schema should not be delayed until an entity is used (at least in case of using JPA), so you can use JPA properties which guarantee this behaviour. If you still find this behaviour occuring, you should make a bug ticket at your JPA provider bugtracker.