【问题标题】:Disable table recreation in Spring Boot application在 Spring Boot 应用程序中禁用表重新创建
【发布时间】:2014-03-25 00:08:49
【问题描述】:

我正在尝试使用 Spring Boot 构建一个简单的 Web 应用程序。当我重新启动应用程序时,所有数据库表都会重新创建。我尝试将 hibernate.hbm2ddl.auto 设置为 updatevalidate 但这没有帮助。

这是我的配置:

@ComponentScan
@EnableAutoConfiguration
@EnableHypermediaSupport
@EnableSpringDataWebSupport
public class ApplicationConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource datasource = new DriverManagerDataSource();
        datasource.setDriverClassName("org.postgresql.Driver");
        datasource.setUrl("jdbc:postgresql://localhost/mydatabase");
        datasource.setUsername("myusername");
        datasource.setPassword("mypassword");
        return datasource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
        LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
        lef.setDataSource(dataSource);
        lef.setJpaVendorAdapter(jpaVendorAdapter);
        lef.setPackagesToScan("my.domain.package");
        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        lef.setJpaProperties(jpaProperties);
        return lef;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        hibernateJpaVendorAdapter.setShowSql(false);
        hibernateJpaVendorAdapter.setGenerateDdl(true);
        hibernateJpaVendorAdapter.setDatabase(Database.POSTGRESQL);
        return hibernateJpaVendorAdapter;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager();
    }

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

使用 --debug 我得到了这个(有些过滤):

2014-02-23 18:17:30.735  INFO 27716 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@66e43eb8: startup date [Sun Feb 23 18:17:30 CET 2014]; root of context hierarchy
2014-02-23 18:17:31.354  INFO 27716 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'pageableResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration; factoryMethodName=pageableResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/web/config/HateoasAwareSpringDataWebConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration; factoryMethodName=pageableResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/web/config/HateoasAwareSpringDataWebConfiguration.class]]
2014-02-23 18:17:31.355  INFO 27716 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'sortResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration; factoryMethodName=sortResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/web/config/HateoasAwareSpringDataWebConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration; factoryMethodName=sortResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/web/config/HateoasAwareSpringDataWebConfiguration.class]]
2014-02-23 18:17:31.726  INFO 27716 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'viewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=thymeleafConfig; factoryMethodName=viewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [be/**************/******/ThymeleafConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=viewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2014-02-23 18:17:32.159  INFO 27716 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'transactionManager': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=applicationConfig; factoryMethodName=transactionManager; initMethodName=null; destroyMethodName=(inferred); defined in class **.**************.******.ApplicationConfig] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; factoryMethodName=transactionManager; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]]
2014-02-23 18:17:32.160  INFO 27716 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'entityManagerFactory': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=applicationConfig; factoryMethodName=entityManagerFactory; initMethodName=null; destroyMethodName=(inferred); defined in class **.**************.******.ApplicationConfig] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; factoryMethodName=entityManagerFactory; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]]
2014-02-23 18:17:32.160  INFO 27716 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'jpaVendorAdapter': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=applicationConfig; factoryMethodName=jpaVendorAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class **.**************.******.ApplicationConfig] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; factoryMethodName=jpaVendorAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]]
2014-02-23 18:17:33.031  INFO 27716 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerByCGLIB$$9ca466b9] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-23 18:17:33.074  INFO 27716 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionAttributeSource' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-23 18:17:33.092  INFO 27716 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionInterceptor' of type [class org.springframework.transaction.interceptor.TransactionInterceptor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-23 18:17:33.102  INFO 27716 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-23 18:17:33.779  INFO 27716 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2014-02-23 18:17:33.779  INFO 27716 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.42
2014-02-23 18:17:33.909  INFO 27716 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-02-23 18:17:33.909  INFO 27716 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3177 ms
2014-02-23 18:17:35.028  INFO 27716 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2014-02-23 18:17:35.028  INFO 27716 --- [ost-startStop-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2014-02-23 18:17:35.124  INFO 27716 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-02-23 18:17:35.385  INFO 27716 --- [ost-startStop-1] o.s.j.d.DriverManagerDataSource          : Loaded JDBC driver: org.postgresql.Driver
2014-02-23 18:17:35.457  INFO 27716 --- [ost-startStop-1] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2014-02-23 18:17:35.592  INFO 27716 --- [ost-startStop-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
2014-02-23 18:17:35.622  INFO 27716 --- [ost-startStop-1] org.hibernate.Version                    : HHH000412: Hibernate Core {4.2.1.Final}
2014-02-23 18:17:35.627  INFO 27716 --- [ost-startStop-1] org.hibernate.cfg.Environment            : HHH000205: Loaded properties from resource hibernate.properties: {hibernate.bytecode.use_reflection_optimizer=false, hibernate.hbm2ddl.auto=validate}
2014-02-23 18:17:35.628  INFO 27716 --- [ost-startStop-1] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2014-02-23 18:17:35.655  INFO 27716 --- [ost-startStop-1] org.hibernate.ejb.Ejb3Configuration      : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2014-02-23 18:17:35.899  INFO 27716 --- [ost-startStop-1] o.h.s.j.c.i.ConnectionProviderInitiator  : HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
2014-02-23 18:17:36.256  INFO 27716 --- [ost-startStop-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL82Dialect
2014-02-23 18:17:36.268  INFO 27716 --- [ost-startStop-1] o.h.e.jdbc.internal.LobCreatorBuilder    : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2014-02-23 18:17:36.284  INFO 27716 --- [ost-startStop-1] o.h.e.t.i.TransactionFactoryInitiator    : HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
2014-02-23 18:17:36.292  INFO 27716 --- [ost-startStop-1] o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
2014-02-23 18:17:36.481  INFO 27716 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
Hibernate: alter table project drop constraint FK_4725849e7c4543e3885bbd3a3a9
2014-02-23 18:17:36.488 ERROR 27716 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table project drop constraint FK_4725849e7c4543e3885bbd3a3a9
2014-02-23 18:17:36.488 ERROR 27716 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: constraint "fk_4725849e7c4543e3885bbd3a3a9" of relation "project" does not exist
Hibernate: alter table project drop constraint FK_56d354acd26e412daa99d5584ff
2014-02-23 18:17:36.489 ERROR 27716 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table project drop constraint FK_56d354acd26e412daa99d5584ff
2014-02-23 18:17:36.489 ERROR 27716 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: constraint "fk_56d354acd26e412daa99d5584ff" of relation "project" does not exist
Hibernate: drop table if exists company cascade
Hibernate: drop table if exists project cascade
Hibernate: create table company (id  serial not null, name varchar(255), primary key (id))
Hibernate: create table project (id  serial not null, reference varchar(255), company int4, primary key (id))
Hibernate: alter table project add constraint FK_4725849e7c4543e3885bbd3a3a9 foreign key (company) references company
2014-02-23 18:17:36.577  INFO 27716 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete

【问题讨论】:

  • 大概就是这一行:hibernateJpaVendorAdapter.setGenerateDdl(true);
  • hibernateJpaVendorAdapter.setGenerateDdl(false) 也无济于事。
  • 您能否使用“--debug”(在命令行上)或-Ddebug(系统属性)运行您的应用程序并附上自动配置报告(或其中任何提到 Hibernate 或 JPA 的部分)?我认为您在那里完全控制了 JPA 配置,但最好检查一下。

标签: spring hibernate postgresql jpa spring-boot


【解决方案1】:

您的配置不是@Configuration 类。

接下来,我建议您使用 Spring Boot 的强大功能。这意味着我建议删除除 DataSource 配置之外的所有内容,并简单地添加一个具有以下属性的 application.properties 文件

spring.jpa.database=POSTGRESQL
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update

这应该会为您提供所需的行为,而编码更少。

如果您的类路径中有 commons-dbcp 或 tomcat-pool 并添加以下属性,您甚至可以删除数据源

spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost/mydatabase
spring.datasource.username=myusername
spring.datasource.password=mypassword

【讨论】:

    【解决方案2】:

    如果您使用的是 spring boot,您可以通过配置文件进行配置。 Hibernate 拥有所有这些可能性:

    1. validate(验证架构)
    2. 更新(如果有变化,更新架构)
    3. create(创建架构)
    4. create-drop(创建架构并在最后删除)

    但是如果你不想做任何事情,spring boot 添加其他机会,使用如下:

    spring:
      jpa:
        hibernate:
          ddl-auto: none
    

    【讨论】:

      【解决方案3】:

      您的ApplicationConfig 不是@Configuration。我想这意味着 Spring Boot 自动配置也将被应用。可以试试添加吗?

      【讨论】:

        【解决方案4】:

        如果您使用的是内存数据库,那么每次启动/停止 Spring Boot 应用程序时 - 除非您提及/配置 Spring Boot 以使用文件系统中的数据库,否则它将重新创建整个事情。

        更新您的@Configuration 或 application.properties 以获取以下属性

        spring.datasource.url=jdbc:h2:file:/Users/user_name/database_file_name
        

        另外检查一下,你不应该在配置中有 spring.datasource.initialization-mode。

        【讨论】:

          猜你喜欢
          • 2016-07-16
          • 2015-08-17
          • 2017-03-20
          • 2016-07-04
          • 2017-11-06
          • 2019-07-24
          • 1970-01-01
          • 1970-01-01
          • 2020-12-21
          相关资源
          最近更新 更多