0

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?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29

1 Answers1

1

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.

Maciej Dobrowolski
  • 11,561
  • 5
  • 45
  • 67
  • I am using OpenJPA and it supports JPA 2.0 spec as of now. This property if from JPA 2.1. – Kalpa Welivitigoda Jul 24 '14 at 05:48
  • @callkalpa for any pre JPA 2.1 implementations you should use vendor specific properties. For `OpenJPA` you can see this url: http://openjpa.apache.org/builds/2.2.0/apache-openjpa/docs/ref_guide_mapping.html . Please note there's also mentioned when property `openjpa.jdbc.SynchronizeMappings` will do its job: `OpenJPA will run the mapping tool on these classes when your application obtains its first EntityManager.`. There's no other way to do it automatically (unless you use `java org.apache.openjpa.jdbc.meta.MappingTool` - which is also mentioned in docs.). – Maciej Dobrowolski Jul 24 '14 at 14:01