0

I am assuming my data.sql script for a H2 database is executing after my application is running, hence, findById()(CRUD Methods) are not fetching any data(NULL). How can I fix this?

Please find my log details:

2020-10-12 18:52:01.361  INFO 30872 --- [         task-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-10-12 18:52:01.491  INFO 30872 --- [         task-1] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.21.Final
2020-10-12 18:52:01.735  INFO 30872 --- [         task-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-10-12 18:52:01.956  INFO 30872 --- [         task-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: drop table if exists monitoring_app CASCADE 
Hibernate: create table monitoring_app (id integer generated by default as identity, grep_parameter varchar(255), service_name varchar(255), hostname varchar(255), log_file_name varchar(255), log_file_path varchar(255), max_failed_retries integer not null, restart_sleep_time_secs integer not null, service_failure char(255), primary key (id))
2020-10-12 18:52:02.982  INFO 30872 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-10-12 18:52:02.990  INFO 30872 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
Hibernate: select monitoring0_.id as id1_0_, monitoring0_.grep_parameter as grep_par2_0_, monitoring0_.service_name as service_3_0_, monitoring0_.hostname as hostname4_0_, monitoring0_.log_file_name as log_file5_0_, monitoring0_.log_file_path as log_file6_0_, monitoring0_.max_failed_retries as max_fail7_0_, monitoring0_.restart_sleep_time_secs as restart_8_0_, monitoring0_.service_failure as service_9_0_ from monitoring_app monitoring0_ where monitoring0_.hostname=?
list is[]
Hibernate: select monitoring0_.id as id1_0_0_, monitoring0_.grep_parameter as grep_par2_0_0_, monitoring0_.service_name as service_3_0_0_, monitoring0_.hostname as hostname4_0_0_, monitoring0_.log_file_name as log_file5_0_0_, monitoring0_.log_file_path as log_file6_0_0_, monitoring0_.max_failed_retries as max_fail7_0_0_, monitoring0_.restart_sleep_time_secs as restart_8_0_0_, monitoring0_.service_failure as service_9_0_0_ from monitoring_app monitoring0_ where monitoring0_.id=?
Hibernate: insert into monitoring_app (id, grep_parameter, service_name, hostname, log_file_name, log_file_path, max_failed_retries, restart_sleep_time_secs, service_failure) values (null, ?, ?, ?, ?, ?, ?, ?, ?)
2020-10-12 18:52:03.679  INFO 30872 --- [         task-2] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-10-12 18:52:03.762  WARN 30872 --- [  restartedMain] 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
2020-10-12 18:52:04.283  INFO 30872 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-10-12 18:52:04.286  INFO 30872 --- [  restartedMain] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-10-12 18:52:04.287  INFO 30872 --- [  restartedMain] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-10-12 18:52:04.298  INFO 30872 --- [  restartedMain] c.m.automation.AutomationApplication     : Started AutomationApplication in 7.785 seconds (JVM running for 8.729)

UPDATE: Please find my data.sql

INSERT INTO EXAMPLE VALUES(default ,'a','b','c','d','e','f',1,2,'y'); INSERT INTO EXAMPLE VALUES(default ,'g','h','i','j','k','l',2,3,'n'); This is mu dao class

@Component public class ExampleDao {

@Autowired
ExampleRepository exampleRepository;

public ArrayList<Example> dbFetchDetails(String var)
{
    ArrayList<Example> exampleList = new ArrayList<>();
    exampleList= exampleRepository.findByVar(var);
   return exampleList;
    }} 

I extend my Repo with CRUDREPOSITORY and define findByVar()

@Repository public interface ExampleRepository extends CrudRepository<Example, Integer> {

ArrayList<Example> findByVar(String Var);

}

@Entity public class Example{

@Id @GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
private String a;
private String b;
private String c;
private String d;
private int e;
private int f;
private String g;
private String h;
private Character i;

//getters setters and contructors added }

Onisha
  • 21
  • 1
  • 4
  • You need to provide your data.sql and the code on how you called your findById() methods. – Shawrup Oct 12 '20 at 15:10
  • Please find the update in the above post – Onisha Oct 14 '20 at 06:41
  • Can you check if the data has been inserted in DB after startup? You can check using h2-console. – Shawrup Oct 14 '20 at 15:23
  • That is the issue, data.sql is not getting inserted before the program executes. It its executing only after the program executes. So my h2 database remains empty and I am unable to fetch anything from the database as it is empty when the findBy() calls to the database are made. Any save() calls I am making during the program is getting executed. Means to say it is able to hit the database. data.sql gets initialised only after the program runs. – Onisha Oct 15 '20 at 08:26
  • I would also want to know why there is a change in the order of parameters of entity in h2 and my entity in java and how t overcome this issue? I have used, @PostConstruct to call my service class method. Can that be the issue? If so, what could be a replacement annotation to start triggering a method in my service layer upon application start without my controller? – Onisha Oct 15 '20 at 08:56
  • Have you looked here? https://stackoverflow.com/questions/45082574/spring-boot-doesnt-load-data-to-initialize-database-using-data-sql – Shawrup Oct 15 '20 at 09:34

1 Answers1

2

So as you said, your @PostConstruct methods are essentially executing before your data.sql executes and fills your local database with data. A simple way around that is to

  1. Remove your @PostConstruct annotations from the methods that need the data.sql to run
  2. Have the classes that have that were using the @PostConstruct methods implement ApplicationListener<ContextRefreshedEvent>

See example below

    @Configuration
    class InitConfiguration implements ApplicationListener<ContextRefreshedEvent> {
    
    @Override
        public void onApplicationEvent(final ContextRefreshedEvent event) {
            init();
        }
    
        //Your method that had your @PostConstruct annotation
        public void init() {
            // The code that needs the data.sql to run
        }
    
    }

sman43212
  • 71
  • 1
  • 3