简体   繁体   中英

How to create database tables from Java code using JPA and JavaDB embedded?

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>

您可以将Hibernate与JPA一起使用,然后使用配置选项hibernate.hbm2ddl.auto=create

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM