Auto generate data schema from JPA annotated entity classes

后端 未结 9 1530
滥情空心
滥情空心 2020-12-12 17:43

I\'m using JPA (Hibernate\'s implementation) to annotate entity classes to persist to a relational database (MySQL or SQL Server). Is there an easy way to auto generate the

相关标签:
9条回答
  • 2020-12-12 18:15

    You can use maven plugin to achieve this.

           <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>
    
    0 讨论(0)
  • 2020-12-12 18:16

    With EclipseLink, you should add property:

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

    As it is said here: http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/p_ddl_generation.htm

    My 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>
    
    0 讨论(0)
  • 2020-12-12 18:18

    You can use hbm2ddl from Hibernate. The docs are here.

    0 讨论(0)
  • 2020-12-12 18:24
    <property name="hibernate.hbm2ddl.auto" value="update"/>
    

    Add the above code in the persistence.xml under properties tag. "update" will create the table when first time you run your code, after that, only update the table structures if any changes in domain object.

    0 讨论(0)
  • 2020-12-12 18:30

    As a related note: Documentation for generating database schemas using EclipseLink JPA can be found here.

    0 讨论(0)
  • 2020-12-12 18:31

    Generate create and drop script for given JPA entities

    We use this code to generate the drop and create statements: Just construct this class with all entity classes and call create/dropTableScript.

    If needed you can use a persitence.xml and persitance unit name instead. Just say something and I post the code too.

    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 讨论(0)
提交回复
热议问题