2008-11-18 114 views
40

我正在使用JPA(Hibernate的實現)來註釋實體類以堅持關係數據庫(MySQL或SQL Server)。有沒有簡單的方法從註釋類自動生成數據庫模式(表創建腳本)?從JPA註釋實體類自動生成數據模式

我仍處於原型設計階段,並預計頻繁更改模式。我希望能夠從註釋代碼中指定和更改數據模型。 Grails類似於它從域類生成數據庫。

+0

退房http://stackoverflow.com/questions/779479/reverse-engineer-ddl-from-jpa-entities – 2009-05-15 19:58:20

回答

13

您可以使用Hibernate的hbm2ddl。文檔是here

+9

他詢問了如何僅從註釋類生成模式。我的團隊想要做同樣的事情。我相信hbm2dll只適用於我團隊不想使用的.hbm.xml映射文件。我不認爲OP也是。 – Omniwombat 2009-07-17 19:32:32

+1

根據「使用Hibernate管理Java持久性」是的,您可以使用hbm2ddl:「Hibernate中自動生成 的先決條件SQL DDL始終是Hibernate映射元數據定義,無論是在XML映射文件還是在Java源代碼註釋中。 – dendini 2013-05-27 15:33:50

9

作爲相關說明:使用EclipseLink JPA生成數據庫模式的文檔可以在here找到。

+0

謝謝你。我的問題在第一次谷歌搜索得到答覆。 – AlanObject 2011-11-25 17:39:06

13

生成創建和給定的JPA實體

我們使用此代碼生成下降和創建報表下降腳本: 就構建這個類的所有實體類,並調用創建/ dropTableScript。

如果需要,您可以使用persitence.xml和persives單位名稱。只要說一下 ,我也會發布代碼。

import java.util.Collection; 
import java.util.Properties; 

import org.hibernate.cfg.AnnotationConfiguration; 
import org.hibernate.dialect.Dialect; 
import org.hibernate.ejb.Ejb3Configuration; 

/** 
* SQL Creator for Tables according to JPA/Hibernate annotations. 
* 
* Use: 
* 
* {@link #createTablesScript()} To create the table creationg script 
* 
* {@link #dropTablesScript()} to create the table destruction script 
* 
*/ 
public class SqlTableCreator { 

    private final AnnotationConfiguration hibernateConfiguration; 
    private final Properties dialectProps; 

    public SqlTableCreator(final Collection<Class<?>> entities) { 

     final Ejb3Configuration ejb3Configuration = new Ejb3Configuration(); 
     for (final Class<?> entity : entities) { 
      ejb3Configuration.addAnnotatedClass(entity); 
     } 

     dialectProps = new Properties(); 
     dialectProps.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect"); 

     hibernateConfiguration = ejb3Configuration.getHibernateConfiguration(); 
    } 

    /** 
    * Create the SQL script to create all tables. 
    * 
    * @return A {@link String} representing the SQL script. 
    */ 
    public String createTablesScript() { 
     final StringBuilder script = new StringBuilder(); 

     final String[] creationScript = hibernateConfiguration.generateSchemaCreationScript(Dialect 
       .getDialect(dialectProps)); 
     for (final String string : creationScript) { 
      script.append(string).append(";\n"); 
     } 
     script.append("\ngo\n\n"); 

     return script.toString(); 
    } 

    /** 
    * Create the SQL script to drop all tables. 
    * 
    * @return A {@link String} representing the SQL script. 
    */ 
    public String dropTablesScript() { 
     final StringBuilder script = new StringBuilder(); 

     final String[] creationScript = hibernateConfiguration.generateDropSchemaScript(Dialect 
       .getDialect(dialectProps)); 
     for (final String string : creationScript) { 
      script.append(string).append(";\n"); 
     } 
     script.append("\ngo\n\n"); 

     return script.toString(); 
    } 
} 
+0

非常好的解決方案!但直接使用persistence.xml對我們來說會更舒適。您可以使用persistence.xml發佈代碼嗎?提前致謝! – 2012-04-26 10:55:55

+0

This line:public SqlTableCreator(final Collection> entities)should be final Collection entities – r590 2017-01-25 00:24:19

2

如果您更喜歡配置在春天那麼這應該是有幫助的:

<!-- CONTAINER-MANAGED JPA Entity manager factory (No need for persistence.xml)--> 
    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
    <property name="dataSource" ref="dataSource"/> 
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/> 
    <!-- Fine Grained JPA properties Create-Drop Records --> 
    <property name="jpaProperties"> 
    <props> 
    <prop key="hibernate.hbm2ddl.auto">create</prop> 
    </props> 
    </property> 
    </bean> 
    <!-- The JPA vendor --> 
    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 
    <!-- <property name="database" value="MySQL"/> --> 
    <property name="showSql" value="true"/> 
    <!-- <property name="generateDdl" value="true"/> --> 
    <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>  
    </bean> 
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 
     <property name="entityManagerFactory" ref="emf" /> 
    </bean> 
2

您可以使用Maven插件來實現這一目標。

 <plugin> 
      <!-- run command "mvn hibernate3:hbm2ddl" to generate DLL --> 
      <groupId>org.codehaus.mojo</groupId> 
      <artifactId>hibernate3-maven-plugin</artifactId> 
      <version>3.0</version> 
      <configuration> 
       <hibernatetool> 
        <classpath> 
         <path location="${project.build.directory}/classes" /> 
         <path location="${project.basedir}/src/main/resources/META-INF/" />            
        </classpath> 

        <jpaconfiguration persistenceunit="galleryPersistenceUnit" />      
        <hbm2ddl create="true" export="false" destdir="${project.basedir}/target" drop="true" outputfilename="mysql.sql" format="true" console="true"/> 
       </hibernatetool> 
      </configuration> 
     </plugin> 
1
<property name="hibernate.hbm2ddl.auto" value="update"/> 

添加上面的代碼中下屬性標籤persistence.xml中。 「更新」將在第一次運行代碼時創建表,之後只更新表結構,如果域對象發生任何更改。

7

由於休眠4.3+現在實現JPA 2.1適當的方法來生成DDL腳本是使用下面的一組JPA 2.1特性:

<property name="javax.persistence.schema-generation.scripts.action" value="create"/> 
<property name="javax.persistence.schema-generation.create-source" value="metadata"/> 
<property name="javax.persistence.schema-generation.scripts.create-target" value="target/jpa/sql/create-schema.sql"/> 

因爲它會在運行時運行,你可能要執行此生成DDL代。 Hibernate4中沒有支持的官方Maven插件,可能是因爲Hibernate團隊正在轉向Gradle。

無論如何,這是JPA 2.1的方法來編程方式生成這個腳本:

import java.io.IOException; 
import java.util.Properties; 

import javax.persistence.Persistence; 

import org.hibernate.jpa.AvailableSettings; 

public class JpaSchemaExport { 

    public static void main(String[] args) throws IOException { 
     execute(args[0], args[1]); 
     System.exit(0); 
    } 

    public static void execute(String persistenceUnitName, String destination) { 
     System.out.println("Generating DDL create script to : " + destination); 

     final Properties persistenceProperties = new Properties(); 

     // XXX force persistence properties : remove database target 
     persistenceProperties.setProperty(org.hibernate.cfg.AvailableSettings.HBM2DDL_AUTO, ""); 
     persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none"); 

     // XXX force persistence properties : define create script target from metadata to destination 
     // persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_CREATE_SCHEMAS, "true"); 
     persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_SCRIPTS_ACTION, "create"); 
     persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_CREATE_SOURCE, "metadata"); 
     persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_SCRIPTS_CREATE_TARGET, destination); 

     Persistence.generateSchema(persistenceUnitName, persistenceProperties); 
    } 

} 

正如你可以看到它是很簡單的!

現在,您可以在AntTask使用,或Maven構建這樣的(Maven的):由於據說這裏

<property name="eclipselink.ddl-generation" value="create-tables"/> 

  <plugin> 
       <artifactId>maven-antrun-plugin</artifactId> 
       <version>1.7</version> 
       <executions> 
        <execution> 
         <id>generate-ddl-create</id> 
         <phase>process-classes</phase> 
         <goals> 
          <goal>run</goal> 
         </goals> 
         <configuration> 
          <target> 
           <!-- ANT Task definition --> 
           <java classname="com.orange.tools.jpa.JpaSchemaExport" 
            fork="true" failonerror="true"> 
            <arg value="${persistenceUnitName}" /> 
            <arg value="target/jpa/sql/schema-create.sql" /> 
            <!-- reference to the passed-in classpath reference --> 
            <classpath refid="maven.compile.classpath" /> 
           </java> 
          </target> 
         </configuration> 

        </execution> 
       </executions> 
      </plugin> 
1

用的EclipseLink,你應該添加屬性: http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/p_ddl_generation.htm

我的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="appDB" transaction-type="JTA"> 
     <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> 
     <jta-data-source>LocalMySQL</jta-data-source> 
     <class>entity.Us</class> 
     <class>entity.Btl</class> 
     <class>entity.Co</class> 
     <properties> 
      <property name="eclipselink.ddl-generation" value="create-tables"/> 
     </properties> 
    </persistence-unit> 
</persistence>