Home > Mobile >  Unable to insert values into h2 database table
Unable to insert values into h2 database table

Time:10-18

I am trying to run a code to get the details of user with a given id.

This is my code.

package com.in28minutes.database.databasedemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.in28minutes.database.databasedemo.jpa.PersonJpaRepository;

@SpringBootApplication
public class JpaDemoApplication implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    PersonJpaRepository repository;

    public static void main(String[] args) {
        SpringApplication.run(JpaDemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        
        logger.info("User id 10001 -> {}", repository.findById(10001));
    }
}

This is my repository:

package com.in28minutes.database.databasedemo.jpa;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

import com.in28minutes.database.databasedemo.entity.Person;

@Repository
@Transactional
public class PersonJpaRepository {
    
    //connect to the database
    @PersistenceContext
    EntityManager entityManager;
    
    public Person findById(int id) {
        return entityManager.find(Person.class, id);
    }
}
package com.in28minutes.database.databasedemo.entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {

    @Id
    @GeneratedValue
    private int id;

    private String name;
    private String location;
    private Date birthDate;

    public Person() {

    }

    public Person(int id, String name, String location, Date birthDate) {
        super();
        this.id = id;
        this.name = name;
        this.location = location;
        this.birthDate = birthDate;
    }

    public Person(String name, String location, Date birthDate) {
        super();
        this.name = name;
        this.location = location;
        this.birthDate = birthDate;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    @Override
    public String toString() {
        return String.format("\nPerson [id=%s, name=%s, location=%s, birthDate=%s]", id, name, location, birthDate);
    }

}

And this is my schema

create table person
(
   id integer not null,
   name varchar(255) not null,
   location varchar(255),
   birth_date timestamp,
   primary key(id)
);


INSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) 
VALUES(10001,  'Ranga', 'Hyderabad',sysdate());
INSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) 
VALUES(10002,  'James', 'New York',sysdate());
INSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) 
VALUES(10003,  'Pieter', 'Amsterdam',sysdate());

I also have spring.h2.console.enabled=true in my application.properties.

2021-10-17 04:17:53.745  INFO 17096 --- [           main] c.i.d.databasedemo.JpaDemoApplication    : Starting JpaDemoApplication using Java 16.0.2 on DESKTOP-Q0GM1GU with PID 17096 (C:\Users\HP\Desktop\database-demo\target\classes started by HP in C:\Users\HP\Desktop\database-demo)
2021-10-17 04:17:53.750  INFO 17096 --- [           main] c.i.d.databasedemo.JpaDemoApplication    : No active profile set, falling back to default profiles: default
2021-10-17 04:17:55.170  INFO 17096 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-10-17 04:17:55.210  INFO 17096 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 14 ms. Found 0 JPA repository interfaces.
2021-10-17 04:17:57.110  INFO 17096 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-10-17 04:17:57.130  INFO 17096 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-10-17 04:17:57.130  INFO 17096 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.54]
2021-10-17 04:17:57.417  INFO 17096 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-10-17 04:17:57.418  INFO 17096 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3557 ms
2021-10-17 04:17:57.512  INFO 17096 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-10-17 04:17:57.924  INFO 17096 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-10-17 04:17:57.968  INFO 17096 --- [           main] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:0af42eb0-d2fc-45af-ad68-57b087b53fc0'
2021-10-17 04:17:58.592  INFO 17096 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-17 04:17:58.733  INFO 17096 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.0.Final
2021-10-17 04:17:59.180  INFO 17096 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-17 04:17:59.662  INFO 17096 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: drop table if exists person CASCADE 
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: create table person (id integer not null, birth_date timestamp, location varchar(255), name varchar(255), primary key (id))
2021-10-17 04:18:01.342  INFO 17096 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-10-17 04:18:01.368  INFO 17096 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-17 04:18:01.656  WARN 17096 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-10-17 04:18:02.194  WARN 17096 --- [           main] o.s.w.s.r.ResourceHttpRequestHandler     : Locations list is empty. No resources will be served unless a custom ResourceResolver is configured as an alternative to PathResourceResolver.
2021-10-17 04:18:02.550  INFO 17096 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-10-17 04:18:02.568  INFO 17096 --- [           main] c.i.d.databasedemo.JpaDemoApplication    : Started JpaDemoApplication in 9.623 seconds (JVM running for 10.727)
Hibernate: select person0_.id as id1_0_0_, person0_.birth_date as birth_da2_0_0_, person0_.location as location3_0_0_, person0_.name as name4_0_0_ from person person0_ where person0_.id=?
2021-10-17 04:18:02.770  INFO 17096 --- [           main] ication$$EnhancerBySpringCGLIB$$6f304a0c : User id 10001 -> null

However, in my result, I am getting the value back as null. Also, I know that I should be getting an error that the table PERSON already exists and it that it should not be declared in the schema, but that is not the case.

After checking the h2 database, I see that none of the values are inserted.

CodePudding user response:

You can try adding spring.jpa.hibernate.ddl-auto=create to your property file. You can check this question here in stackoverflow or from the documentation.

CodePudding user response:

Apparently, I just had to include spring.jpa.defer-datasource-initialization = true in my properties file.

  • Related