A
A
Araya2021-06-15 10:54:51
Hibernate
Araya, 2021-06-15 10:54:51

Tables are not enriched when Entity is created?

When enriching a PostgreSQL table with data, using a SQL file and mode

spring.jpa.hibernate.ddl-auto=create-drop
I catch an exception - PSQLException .

Entity - Book :
@Data
@Entity
@Table(name = "books", schema = "public")
@NoArgsConstructor
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String priceOld;
    private String price;
}

Settings - application.properties :
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=create-drop

SQL file - data.sql :
insert into books (title, price_old, price) values ('about animals', '$17.99', '$5.99');


Exception - PSQLException :
ERROR: relation "books" does not exist

Very similar to running SQL first and then creating the database, hence not finding the table.
If the database is created, then the script is executed correctly.
Happened after migrating from H2 to PostgreSQL.

Is it possible to change the order of execution (i.e. create a table, then fill it), or is there an adequate, alternative solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2021-06-15
@Araya

Good afternoon!
Yes, of course, the sql file is executed first.
It is possible to implement on a miscellaneous:
1) Try to take out DDL requests in sql a file. (schema.sql)
2) Or vice versa, initialize the contents of data.sql using java code. For example, implement the CommandLineRunner interface
3) Try to use the FlyWay lib for migrations
spring.jpa.hibernate.ddl-auto=create-drop
This means that all created tables will be dropped and at the time of start there are no tables in the database where your inserts should be added.
Useful information - https://www.baeldung.com/spring-boot-data-sql-and-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question