【问题标题】:Spring application not creating the table on a Postgres databaseSpring 应用程序未在 Postgres 数据库上创建表
【发布时间】:2019-09-02 04:16:27
【问题描述】:

Spring 不会在我的 Postgres 数据库中创建@Entity 类中指定的表

我已经尝试了 StackOverflow 中给出的很多解决方案,例如 application.properties 中的一些更改、更改方言、设置架构等。我检查了我的数据库权限和还有用户/密码信息,一切都很好。

application.properties
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.datasource.url= jdbc:postgresql://localhost:5432/produtosapirest
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.produtos</groupId>
<artifactId>apirest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apirest</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Produto.java
package produtos.api.models;

import java.io.Serializable;
import java.math.BigDecimal;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="TB_PRODUTO")
public class Produto implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;

private String nome;
private BigDecimal quantidade;
private BigDecimal valor;

public long getId() {
    return id;
}
public void setId(long id) {
    this.id = id;
}
public String getNome() {
    return nome;
}
public void setNome(String nome) {
    this.nome = nome;
}
public BigDecimal getQuantidade() {
    return quantidade;
}
public void setQuantidade(BigDecimal quantidade) {
    this.quantidade = quantidade;
}
public BigDecimal getValor() {
    return valor;
}
public void setValor(BigDecimal valor) {
    this.valor = valor;
}

}

终端
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-04-11 10:21:00.011  INFO 16132 --- [  restartedMain] com.produtos.apirest.ApirestApplication  : Starting ApirestApplication on venancio-MS-7817 with PID 16132 (/home/brenorios/eclipse-workspace/apirest/target/classes started by brenorios in /home/brenorios/eclipse-workspace/apirest)
2019-04-11 10:21:00.014  INFO 16132 --- [  restartedMain] com.produtos.apirest.ApirestApplication  : No active profile set, falling back to default profiles: default
2019-04-11 10:21:00.077  INFO 16132 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-04-11 10:21:00.077  INFO 16132 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-04-11 10:21:00.880  INFO 16132 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-04-11 10:21:00.901  INFO 16132 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 14ms. Found 0 repository interfaces.
2019-04-11 10:21:01.283  INFO 16132 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$84f3c51d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-04-11 10:21:01.672  INFO 16132 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-04-11 10:21:01.698  INFO 16132 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-04-11 10:21:01.698  INFO 16132 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-04-11 10:21:01.778  INFO 16132 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-04-11 10:21:01.778  INFO 16132 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1701 ms
2019-04-11 10:21:01.988  INFO 16132 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-04-11 10:21:02.137  INFO 16132 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-04-11 10:21:02.178  INFO 16132 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-04-11 10:21:02.226  INFO 16132 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.9.Final}
2019-04-11 10:21:02.227  INFO 16132 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-04-11 10:21:02.343  INFO 16132 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-04-11 10:21:02.455  INFO 16132 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
2019-04-11 10:21:02.659  INFO 16132 --- [  restartedMain] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
2019-04-11 10:21:02.663  INFO 16132 --- [  restartedMain] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@3046a8a9
2019-04-11 10:21:02.834  INFO 16132 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-04-11 10:21:02.852  INFO 16132 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2019-04-11 10:21:03.042  INFO 16132 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-11 10:21:03.087  WARN 16132 --- [  restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-04-11 10:21:03.347  INFO 16132 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-11 10:21:03.349  INFO 16132 --- [  restartedMain] com.produtos.apirest.ApirestApplication  : Started ApirestApplication in 3.783 seconds (JVM running for 4.149)
ApirestApplication.java:
package com.produtos.apirest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApirestApplication {

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

}

根据我正在遵循的教程,此设置应该会导致在 postgres 数据库中创建表,但它不会发生。

【问题讨论】:

  • 我建议使用spring.jpa.show-sql=true 来调试和识别您的应用程序的问题。它将打印 JPA 的日志,以便您了解幕后发生的事情。

标签: spring postgresql hibernate spring-boot jdbc


【解决方案1】:

我刚试过你的源代码,这里是日志:

2019-04-11 19:58:59.345  INFO 15520 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
2019-04-11 20:02:42.971  INFO 15520 --- [  restartedMain] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
2019-04-11 20:02:42.975  INFO 15520 --- [  restartedMain] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@7893aaa9
2019-04-11 20:02:44.848  WARN 15520 --- [  restartedMain] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Warning Code: 0, SQLState: 00000
2019-04-11 20:02:44.848  WARN 15520 --- [  restartedMain] o.h.engine.jdbc.spi.SqlExceptionHelper   : CREATE TABLE / PRIMARY KEY will create implicit index "tb_produto_pkey" for table "tb_produto"
2019-04-11 20:02:44.850  INFO 15520 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-04-11 20:02:44.863  INFO 15520 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2019-04-11 20:02:45.067  INFO 15520 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-11 20:02:45.111  WARN 15520 --- [  restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning

您可以看到该表是在实例 20:02:44.848 处创建的。这是在上一个日志的 2 分钟之后。检查 @EnableAutoConfiguration 是否已设置。我已将它作为@SpringBootApplication 的一部分启用。

等到你看到打印出来的语句 - “Done---”通过改变你的 Application.java:

package produtos.api;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

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

    @Bean
    public CommandLineRunner demo() {
        return (args) -> {
            System.out.println("Done---");
        };
    }
}

【讨论】:

  • 我在 @SpringBootApplication 注释所在的主文件中添加了代码。
  • @James Jithin @EnableAutoConfiguration 不需要明确设置,因为它将是@SpringBootApplication 的一部分。
  • @darshgohel,和我的回答中提到的一样!
  • @JamesJithin,我的错,也许我解释错了。 Check for @EnableAutoConfiguration is set,这让我很困惑。这就是我发表评论的原因。
  • @darshgohel,别担心!
【解决方案2】:

您缺少 Postgres 方言。您可以尝试在属性/yml 文件中添加 Postgres 方言,如下所示:

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

【讨论】:

    【解决方案3】:

    你的问题可能就在这里,

    spring.jpa.hibernate.ddl-auto=update
    

    如果您阅读更多关于此Here 的信息,您可以识别出来,

    例如,update 操作将尝试添加新列、约束等,但绝不会删除以前可能存在但不再作为先前运行的对象模型的一部分的列或约束。

    所以我会根据您的要求建议您使用createcreate-drop

    注意:

    1. createcreate-drop 将在您每次运行应用程序时创建数据库。因此,如果您不希望这种情况发生,请在创建数据库后将设置更改为 update
    2. 请勿在生产环境中使用此配置。

    【讨论】:

      【解决方案4】:

      我只是认为这是一个愚蠢的错误。我的主包和模型包的名称结构不同,所以 Spring 没有得到我的模型包。

      之前: com.produtosapirest2 com.produtosapi.models

      之后: com.produtosapirest2 com.produtosapirest2.models

      【讨论】:

      • 谢谢,就是这样。我很笨。
      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      相关资源
      最近更新 更多