1

I'm new to programming and I'm trying to read a json and store in a database using springboot, when i use H2 i dont have to create table structure it creates on its own but when i use postgres i get errors that unable to find table. is there anyway to create tables automatically in postgres ?

How do they work and postgres is not able create tables on its own, Am i doing anything wrong?`

 spring.datasource.url=jdbc:h2:mem:testdb
 spring.datasource.driverClassName=org.h2.Driver
 spring.datasource.username=sa
 spring.datasource.password=
 spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
 spring.h2.console.enabled=true

spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/MyDB
spring.datasource.username=postgres
spring.datasource.password=1234
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
  • No database creates tables on its own. Something **has** to run a `CREATE TABLE` statement. In this case it's probably JPA that creates the tables automatically for H2, but not for Postgres –  Apr 08 '21 at 09:59

2 Answers2

1

There's a property you need to set for PostgreSQL to automatically create the tables on startup:

spring.jpa.hibernate.ddl-auto=update

Or if you want to start from a clean database everytime:

spring.jpa.hibernate.ddl-auto=create

For embedded databases like H2, Spring Boot will set spring.jpa.hibernate.ddl-auto=create automatically

See also this 12-year old question about why you should not do that in production: Hibernate: hbm2ddl.auto=update in production?

In production, you should manage the database tables outside of your application, or use something like Liquibase or Flyway

GeertPt
  • 16,398
  • 2
  • 37
  • 61
0

If the database is embedded the default value of spring.jpa.hibernate.ddl-auto is create-drop. If not, default value is none. Check this out - https://docs.spring.io/spring-boot/docs/1.1.0.M1/reference/html/howto-database-initialization.html