0

My application uses JPA and JavaDB in embedded mode. In the persistence.xml file I use this property:

<property name="javax.persistence.jdbc.url" value="jdbc:derby:meuspiladb;create=true" />

so an empty database will be created if it does not exist yet.

Currently I have a create_tables.sql file where I put the SQL code to create the tables, and then I run it manually after the database is created. I would like to make this be automatic but I don't know how.

If the database is new I have to create the tables. What is the best way to create them from Java code?


My persistence.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="MeusPila3_PU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>br.meuspila.corretora.Corretora</class>
    <class>br.meuspila.ativo.Ativo</class>
    <class>br.meuspila.bolsa.Bolsa</class>
    <class>br.meuspila.movimento.Movimento</class>
    <class>br.meuspila.provento.Provento</class>
    <class>br.meuspila.operacao.Operacao</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:meuspiladb;create=true" />
      <property name="javax.persistence.jdbc.user" value="APP"/>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
    </properties>
  </persistence-unit>
</persistence>
ceklock
  • 6,143
  • 10
  • 56
  • 78

1 Answers1

1

You can use Hibernate with JPA, then use configuration option hibernate.hbm2ddl.auto=create.

  • How? Are the tables created from the entities? – ceklock Oct 28 '13 at 18:58
  • No, from the mapping but entities are used to create it. Check the documentation for *persistence.xml* how to map entities to classes. –  Oct 28 '13 at 19:00
  • I think I already have the mapping. Sorry, but I will not use Hibernate. I am using EclipseLink, I think it is similar... I just dont know if it is better to use pure sql to create the tables or I create them from the entities/mapping... I don't know if the entities will generate the tables exactly like the sql. – ceklock Oct 28 '13 at 19:21
  • Your hint is for Hibernate, but I found something similar for EclipseLink, thanks! – ceklock Oct 28 '13 at 19:50
  • 1
    not exactly but if you generate entities from sql then it will be similar. –  Oct 28 '13 at 21:05