Spring Boot - JPA Hibernate无法自动创建表格?

4

我在我的application.properties文件中有这段代码:

# Spring DataSource
spring.datasource.driverClassName=org.postgresql.Driver
spring.sql.init.mode=always
spring.sql.init.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/dbname
spring.datasource.username=postgres
spring.datasource.password=root

# JPA-Hibernate
spring.jpa.generate-ddl=true
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create

# https://dev59.com/9lcP5IYBdhLWcg3wvMdF
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

# Optimization for POSTGRES queries
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect

您可以看到,我已经添加了spring.jpa.hibernate.ddl-auto=create这行,但是JPA仍然没有创建表。我必须手动创建它们才能让项目编译通过。有什么问题吗?


也许你在实体类中使用了一些被JPA保留的关键字作为字段名。 - amir-rad
9个回答

5

您可以使用 spring.jpa.hibernate.ddl-auto=update,并检查您是否在实体类上方使用了 @Table(name="table_name") 注释。

这可能会有所帮助。


2
有几种可能的原因:
Your entity classes are in the same or in a sub-package relative one where you have you class with @EnableAutoConfiguration. If not then your spring app does not see them and hence will not create anything in db

Your application.properties must be in src/main/resources folder.

尝试添加 @ComponentScan("包含实体类、配置和服务的包名")。

1

请检查您是否已将@Entity注释添加到您的模型类中。此外,请确保模型类位于所需的包中。


0
这是你需要做的事情:
1- 在你想要作为表格查看的每个类上添加@Entity注释
2- 在你的application.properties文件中添加以下行:
spring.jpa.generate-ddl=true
spring.datasource.url=jdbc:postgresql://localhost:5432/dbname
spring.datasource.username=postgres
spring.datasource.password=root
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.show-sql=false 
spring.jpa.hibernate.ddl-auto=create-drop

0
请检查以下注释: 1- 在您的类上使用@Table(name:),@Entity。 2- 在每个字段上使用@Column(name:)。

0
我的问题是我创建了一个新的模型,其中一个字段的列名是保留的 SQL 关键字(例如 "start"、"end"、"table" 等)。由于语法错误,表格创建将失败,但应用程序仍然因某种原因启动“成功”。

0
确保您的导入来自javax.persistence而不是jakarta.persistence。在一个项目中,我导入了jakarta.persistence.Entity以及其他注释,花了我一段时间才解决这个问题。一旦我将所有注释导入切换到javax.persistence,它就可以正常工作了。

0

你可以在application.properties文件中使用这个,它对我有效。

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE


spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.data.jpa.repositories.enabled=true
spring.datasource.url=jdbc:postgresql://localhost:5432/dbname
spring.datasource.username=postgres
spring.datasource.password=password
spring.datasource.driverClassName=org.postgresql.Driver

同时在实体类上方使用此注解。

 @Entity
 @Table(name=" give the name of the table you want ")

0

我遇到了这个问题,所以在application.properties文件中,我进行了替换。

spring.jpa.hibernate.ddl.auto=update

使用

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update

此外,我添加了(可选)

spring.jpa.defer-datasource-initialization=true
spring.jpa.database = MYSQL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接