Home > Blockchain >  create an api rest using spring boot and h2 database
create an api rest using spring boot and h2 database

Time:03-28

I am trying to create my very first api using spring boot and a H2 database in order to do some CRUD operations , I have a data.sql file in order to create the employe table and insert some values I also configure H2 database in the application.properrties file as so :spring.h2.console.enabled=true in order to see the data.And everything go as planned I can see my data in the localhost . The problem is that after I add my model class Employe.java i can't see my data anymore the table has no value anymore .

import lombok.Data;

import javax.persistence.*;

@Data
@Entity
@Table(name = "employees")  
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name="first_name")
    private String firstName;
    
    @Column(name="last_name")
    private String lastName;
    
    private String mail;
    
    private String password;
    
}

data.sql

CodePudding user response:

  • Check the "spring.jpa.hibernate.ddl-auto" config Ref: [https://docs.spring.io/spring-boot/docs/1.1.0.M1/reference/html/howto-database-initialization.html][1]
  • Try validating the startup log to note DataSourceAutoConfiguration execution order. The Entity bean maybe recreating the table.

You can either manage ddl-auto property or exclude DataSourceAutoConfiguration by adding autoconfigure.exclude to control DDLs

CodePudding user response:

The problem was because of the spring boot version , With Spring Boot 2.5.1 and above it seems like the data.sql file is executed before the model class which explain that the values are deleted . For anyone who face the same problem as me please refer to the next ressource : https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.5-Release-Notes

So you should either downgrade your spring boot version or add spring.jpa.hibernate.ddl-auto= none in the application.properties file

  • Related