简体   繁体   English

如何使用嵌入式JPA和JavaDB从Java代码创建数据库表?

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

My application uses JPA and JavaDB in embedded mode. 我的应用程序在嵌入式模式下使用JPA和JavaDB。 In the persistence.xml file I use this property: persistence.xml文件中,我使用以下属性:

<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. 当前,我有一个create_tables.sql文件,在其中放置了SQL代码来创建表,然后在创建数据库后手动运行它。 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? 用Java代码创建它们的最佳方法是什么?


My persistence.xml file: 我的persistence.xml文件:

<?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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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