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>

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

How? Are the tables created from the entities?
No, from the mapping but entities are used to create it. Check the documentation for persistence.xml how to map entities to classes.
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.
Your hint is for Hibernate, but I found something similar for EclipseLink, thanks! <property name="eclipselink.ddl-generation" value="create-tables"/>
not exactly but if you generate entities from sql then it will be similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.