Spring Boot休眠两个架构PSQLException:错误:架构“ myschema”不存在

时间:2018-07-29 07:28:22

标签: postgresql hibernate spring-boot spring-data-jpa

我有两个具有相同模型的模式,但是除了Postgres之外,它没有以某种方式工作,但出现相同的错误却创建了模式。其他数据库即使在h2嵌入式数据库上也不会创建架构。

我知道在两个数据库上创建相同的实体是很丑陋的,但是以某种方式我找到了一个用例。这不是讨论。

错误

  

由以下原因引起:org.postgresql.util.PSQLException:错误:架构“ myschema”   不存在

错误堆满

  GenerationTarget encountered exception accepting command : Error
  executing DDL via JDBC Statement
  org.hibernate.tool.schema.spi.CommandAcceptanceException: Error
  executing DDL via JDBC Statement  at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
    at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:375)
    at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359)
    at org.hibernate.tool.schema.internal.SchemaDropperImpl.applyConstraintDropping(SchemaDropperImpl.java:331)
    at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:230)
    at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154)
    at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126)
    at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:144)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:312)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1765)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1702)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:579)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:139)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)     
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)  
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)  
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)     
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)   
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.postgresql.util.PSQLException: ERROR: schema "myschema" does not exist
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:307)
    at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:293)
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:270)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:266)     
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
    ... 59 common frames omitted

测试仅适用于postgres:

@SpringBootTest
@RunWith(SpringRunner.class)
public class AcceptanceTestTest {

@Autowired
private TestRepository testRepository;

@Autowired
private LiveRepository liveRepository;

@Test
    public void testTwoDataSources() {
        Event event_one = prepareEvent();
        Event event_two = prepareEvent();

        liveRepository.save(event_one);
        testRepository.save(event_one);

        testEventRepository.save(event_two);

        assertThat(testRepository.count(), is(2L));
        assertThat(liveRepository.count(), is(1L));
    }

Application.yml

spring:
  jpa:
    show-sql: false
    hibernate:
      ddl-auto: create-drop
      use-new-id-generator-mappings: true
  datasource:
    url: jdbc:postgresql://localhost:5432/postgres
    username: postgres
    password:
    driverClassName: org.postgresql.Driver
    schema:
      live: myschema
      test: test
  test:
    mockmvc:
      print: system_err

MySchemaConfig

@Configuration
@EnableJpaRepositories(basePackages = "berlin.yuna.acceptancetest.repositories.myschema", entityManagerFactoryRef = "livePersistenceEntityManager", transactionManagerRef = "livePersistenceTransactionManager")
public class LivePersistenceConfig {

    @Autowired
    private Environment env;

    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean livePersistenceEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(MySchemaDataSource());
        em.setPackagesToScan("berlin.yuna.acceptancetest.repositories.myschema", "berlin.yuna.acceptancetest.model");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setShowSql(Boolean.valueOf(env.getProperty("spring.jpa.show-sql")));
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put(DEFAULT_SCHEMA, env.getProperty("spring.datasource.schema.live"));
        properties.put(DIALECT, detectDatabasePlatform(env.getProperty("spring.datasource.driverClassName"), env.getProperty("spring.jpa.database-platform")));
        properties.put(HBM2DDL_AUTO, env.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.put(SHOW_SQL, env.getProperty("spring.jpa.show-sql"));
        properties.put(HBM2DLL_CREATE_SCHEMAS, String.valueOf(requireNonNull(env.getProperty("spring.jpa.hibernate.ddl-auto")).toLowerCase().contains("create")));
        properties.put(HBM2DDL_DATABASE_ACTION, env.getProperty("spring.jpa.hibernate.ddl-auto"));
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean
    public DataSource mySchemaDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setDriverClassName(requireNonNull(env.getProperty("spring.datasource.driverClassName")));
        dataSource.setSchema(env.getProperty("spring.datasource.schema.live"));
        return dataSource;
    }

    @Primary
    @Bean
    public PlatformTransactionManager livePersistenceTransactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(livePersistenceEntityManager().getObject());
        return transactionManager;
    }

TestSchema

@Configuration
@EnableJpaRepositories(basePackages = "berlin.yuna.acceptancetest.repositories.test", entityManagerFactoryRef = "testPersistenceEntityManager", transactionManagerRef = "testPersistenceTransactionManager")
public class TestPersistenceConfig {

    @Autowired
    private Environment env;

    @Bean
    public LocalContainerEntityManagerFactoryBean testPersistenceEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(testDataSource());
        em.setPackagesToScan("berlin.yuna.acceptancetest.repositories.myschema", "berlin.yuna.acceptancetest.model");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setShowSql(Boolean.valueOf(env.getProperty("spring.jpa.show-sql")));
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put(HBM2DDL_AUTO, env.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.put(DEFAULT_SCHEMA, env.getProperty("spring.datasource.schema.test"));
        properties.put(SHOW_SQL, env.getProperty("spring.jpa.show-sql"));
        properties.put(HBM2DLL_CREATE_SCHEMAS, String.valueOf(requireNonNull(env.getProperty("spring.jpa.hibernate.ddl-auto")).toLowerCase().contains("create")));
        properties.put(HBM2DDL_DATABASE_ACTION, env.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.put(DIALECT, detectDatabasePlatform(env.getProperty("spring.datasource.driverClassName"), env.getProperty("spring.jpa.database-platform")));
        em.setJpaPropertyMap(properties);
        return em;
    }

    @Bean
    public DataSource testDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setDriverClassName(requireNonNull(env.getProperty("spring.datasource.driverClassName")));
        dataSource.setSchema(env.getProperty("spring.datasource.schema.test"));
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager testPersistenceTransactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(testPersistenceEntityManager().getObject());
        return transactionManager;
    }

0 个答案:

没有答案