如何通过Persistence.generateSchema()生成DDL?

时间:2015-09-22 07:20:06

标签: hibernate jpa-2.1

<?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="safety" transaction-type="JTA">
    <jta-data-source>java:/jdbc/MyDataSource</jta-data-source>
    <properties>
      <property name="javax.persistence.schema-generation.scripts.action" value="create"/>
      <property name="javax.persistence.schema-generation.scripts.create-target" value="create.ddl"/>
      <property name="hibernate.default_schema" value="safety"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.format_sql" value="false"/>
      <property name="hibernate.use_sql_comments" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

这是我的persistence.xml。如何通过Persistence.generateSchema()生成数据库模式?

public class SchemaGenerator {
    public static void main(String args[]) {
        Map<String, Object> properties = new HashMap<String, Object>();
        //adding some properties
        Persistence.generateSchema("safety", properties);
    }
}

它给了我这个错误:org.hibernate.engine.jndi.JndiException:解析JNDI名称[java:/ jdbc / MyDataSource]时出错。

但是,它不需要连接我的数据库,因为我只需要生成ddl。

1 个答案:

答案 0 :(得分:0)

您必须将属性connection.provider_class设置为org.hibernate.service.jdbc.connections.internal.UserSuppliedConnectionProviderImpl。这样他就不会尝试加载JNDI源。

这是我使用 Ant Hibernate Tool 生成离线模式的generation.properties

hibernate.dialect=...
hibernate.connection.provider_class=org.hibernate.service.jdbc.connections.internal.UserSuppliedConnectionProviderImpl
javax.persistence.validation.mode=ddl, callback
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false