PersistenceException:未找到用于名为 default 的持久性单元的模式生成的持久性提供程序

PersistenceException: No persistence provider found for schema generation for persistence-unit named default

我已经尝试设置一个 gradle 任务来运行一个 java main class 来生成一个 SQL 模式。

我没有persistence.xml配置文件。

这是我的配置和代码:

我的gradle任务:

task JpaSchemaExport(type: JavaExec){
       description "Exports Jpa schema"
       dependsOn compileJava
       main = "com.bignibou.tools.jpa.JpaSchemaExport"
       classpath = sourceSets.main.runtimeClasspath + configurations.compile
    }

我的导出工具:

public class JpaSchemaExport {

    public static void main(String[] args) throws IOException {
        // execute(args[0], args[1]);
        execute("default", "build/schema.sql");
        System.exit(0);
    }

    public static void execute(String persistenceUnitName, String 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);
    }
}

我的数据配置:

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setPackagesToScan("com.bignibou.domain");
    emf.setDataSource(dataSource);
    emf.setPersistenceProvider(new HibernatePersistenceProvider());
    emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    emf.setJpaPropertyMap(propertiesMap());
    return emf;
}

private Map<String, String> propertiesMap() {
    Map<String, String> propertiesMap = new HashMap<>();
    propertiesMap.put("hibernate.dialect", hibernateDialect);
    propertiesMap.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);
    propertiesMap.put("hibernate.ejb.naming_strategy", hibernateEjbNamingStrategy);
    propertiesMap.put("hibernate.connection.charSet", hibernateConnectionCharset);
    propertiesMap.put("hibernate.show_sql", hibernateLogSqlInfo);
    propertiesMap.put("hibernate.format_sql", hibernateLogSqlInfo);
    propertiesMap.put("hibernate.use_sql_comments", hibernateLogSqlInfo);
    propertiesMap.put("hibernate.generate_statistics", hibernateGenerateStatistics);
    propertiesMap.put("hibernate.cache.use_second_level_cache", hibernateCacheUseSecondLevelCache);
    propertiesMap.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory");
    propertiesMap.put("javax.persistence.sharedCache.mode", "ENABLE_SELECTIVE");
    return propertiesMap;
}

这是我得到的异常:

Exception in thread "main" javax.persistence.PersistenceException: No persistence provider found for schema generation for persistence-unit named default
 at javax.persistence.Persistence.generateSchema(Persistence.java:93)
 at com.bignibou.tools.jpa.JpaSchemaExport.execute(JpaSchemaExport.java:31)
 at com.bignibou.tools.jpa.JpaSchemaExport.main(JpaSchemaExport.java:14)

编辑:我确实收到警告:

:bignibou-server:JpaSchemaExport
2015-05-16 14:46:44,423 [main] WARN  org.hibernate.ejb.HibernatePersistence - HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
2015-05-16 14:46:44,423 [main] WARN  org.hibernate.ejb.HibernatePersistence - HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
2015-05-16 14:46:44,423 [main] WARN  org.hibernate.ejb.HibernatePersistence - HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Exception in thread "main" javax.persistence.PersistenceException: No persistence provider found for schema generation for persistence-unit named default
 at javax.persistence.Persistence.generateSchema(Persistence.java:93)
 at com.bignibou.tools.jpa.JpaSchemaExport.execute(JpaSchemaExport.java:32)
 at com.bignibou.tools.jpa.JpaSchemaExport.main(JpaSchemaExport.java:14)
:bignibou-server:JpaSchemaExport FAILED 

您的代码非常好而且干净。服务器启动时是否有任何其他警告,如 log4j 属性丢失..等,

我认为问题与某些缺少的 jar 或类路径条目有关,但不确定。

据我从你的代码中可以看出,你的 JpaSchemaExport 没有在 Spring 上下文中执行。

当您从 Gradle 或命令行 运行 您的 JpaSchemaExport 时,您创建了自己的 EntityManager,它与 Spring 无关并寻找META-INF 目录中的 persistence.xml 文件。对于 Spring 引导应用程序,不需要此文件,因此可能不存在。

当我 运行 看起来与你的 JpaSchemaExport 相似的东西时 输出类似于

[main] INFO  o.h.j.b.i.PersistenceXmlParser - HHH000318: Could not find any META-INF/persistence.xml file in the class path
[main] DEBUG o.h.jpa.HibernatePersistenceProvider - Located and parsed 0  persistence units; checking each 
[main] DEBUG o.h.jpa.HibernatePersistenceProvider - Found no matching persistence units Exception in thread "main"
javax.persistence.PersistenceException: No persistence provider found
for schema generation for persistence-unit named default    at
javax.persistence.Persistence.generateSchema(Persistence.java:93)   at
com.example.springboot.jpa.JpaSchemaExport.execute(JpaSchemaExport.java:42)
    at
com.example.springboot.jpa.JpaSchemaExport.main(JpaSchemaExport.java:14)

一个 Spring 引导命令行应用程序(具有 Spring 上下文的应用程序)看起来像:

@SpringBootApplication
public class Application implements CommandLineRunner {


    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

    @Override
    public void run(String... strings) throws Exception {

    }

}

即您的 JpaSchemaExport 可能会改写为

@SpringBootApplication
public class JpaSchemaExport implements CommandLineRunner {


    public static void main(String[] args) {
        // maybe activate a special spring profile to enable 
        // "hibernate.hbm2ddl.auto", validate | update | create | create-drop
        // AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none" 
        // AvailableSettings.SCHEMA_GEN_CREATE_SCHEMAS, "true"
        // AvailableSettings.SCHEMA_GEN_SCRIPTS_ACTION, "create"
        // AvailableSettings.SCHEMA_GEN_CREATE_SOURCE, "metadata"
        // AvailableSettings.SCHEMA_GEN_SCRIPTS_CREATE_TARGET, destination

        SpringApplication.run(JpaSchemaExport.class);
    }

    @Override
    public void run(String... strings) throws Exception {
       // nothing needed here 
    }

}

作为替代方案,您可以创建一个 META-INF/persistence.xml,它可以被您的 Spring 引导应用程序以及您的 JpaSchemaExport.

使用

似乎 Persistence.generateSchema() 使用包含 PersistenceProviderResolverPersistenceProviderResolverHolder 来获取所有可用 PersistenceProvider 的列表。也许你应该在调用 Persistence.generateSchema().

之前尝试将你自己的 PersistenceProviderResolver (只有 2 种方法)实现到 return 你想使用的那个(org.hibernate.jpa.HibernatePersistenceProvider
PersistenceProviderResolverHolder.setPersistenceProviderResolver(new PersistenceProviderResolver() {

    public List<PersistenceProvider> getPersistenceProviders() {
        return Collections.singletonList(new HibernatePersistenceProvider());
    }

    public void clearCachedProviders() {}
});

您需要为使用以下方法以编程方式创建的持久性单元设置显式名称,然后确保调用 afterPropertiesSet() 方法:

emf.setPersistenceUnitName( "puname" );
...
emf.afterPropertiesSet();

使用此名称而不是 "default"

来引用您的持久性单元

正在使用 Spring 引导应用程序生成架构:

import org.hibernate.jpa.AvailableSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import java.util.Properties;

@SpringBootApplication
public class JpaSchemaExport implements CommandLineRunner {
    @Autowired LocalContainerEntityManagerFactoryBean entityManagerFactory;

    public static void main(String... args) {
        new SpringApplicationBuilder(JpaSchemaExport.class).run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        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, "./generated-schema.ddl");

        // generate sql with semicolon - workaround for HHH-10278
        String systemLineSeparator = System.getProperty("line.separator");
        System.setProperty("line.separator", ';' + systemLineSeparator);
        // get a persistence provider from spring context
        entityManagerFactory.getJpaVendorAdapter().getPersistenceProvider().generateSchema(entityManagerFactory.getPersistenceUnitInfo(), persistenceProperties);

        System.setProperty("line.separator", systemLineSeparator);
        System.exit(0);
    }

}

如果我不使用 META-INF/persistence。xml,则无法通过名称找到持久性单元。

我不得不注入 EntityManagerFactory:

@Autowired private LocalContainerEntityManagerFactoryBean emf;

... 并通过 info 对象找到持久性单元:

PersistenceProvider provider = emf.getJpaVendorAdapter().getPersistenceProvider();
provider.generateSchema(emf.getPersistenceUnitInfo(), persistenceProperties);

这对我有用。我希望它也能帮助到其他人。