Unable to see data in in memor h2 data base

Viewed 49

I am trying to add few initial values in the in memory h2 database with the base class:

package com.example.demo.user;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import java.util.Date;

@Entity
public class User {

    @Id
    @GeneratedValue
    private Integer id;

    @Size(min=2,message = "Name length >= 2")
    private String name;

    @Past
    private Date dob;

    public User(Integer id, String name, Date dob) {
        this.id = id;
        this.name = name;
        this.dob = dob;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", dob=" + dob +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }
}

data.sql - insert into user values(1,sysdate(),'h'); schema.sql - create table user (id integer not null, dob timestamp, name varchar(255), primary key (id))

application.properties:

spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.data.jpa.repositories.bootstrap-mode=default

unable to see the data. Initialising through commandlinerunner worked. The log does not show the command being executed. but if i try removing schema.sql, throws error.

h2 sql command

1 Answers

Spring will use those scripts schema.sql and data.sql and after that it will also use your entity layer and annotations to create-drop the schema again, meaning the previous changes with the scripts are overwritten.

Since you provide your own schema.sql , it means that you don't need the ORM vendor to create the schema for you based on the entity annotations that you have.

In this case you can procced and declare the property spring.jpa.hibernate.ddl-auto= none

This will not allow the ORM vendor to overwrite what you do with your scripts and only those scripts will be used when loading the application.

PS: spring.jpa.hibernate.ddl-auto= create-drop was already by default defined for you from spring automatically as you have an embedded database selected.

Related