3

I want to make a desktop application using JavaFx, Spring Boot and Spring Data JPA with H2 as my database . The problem is that I am trying to run Junit to save data locally in a directory but every time I run Junit the data is being lost.

My application.properties file;

spring.output.ansi.enabled=ALWAYS                    
spring.datasource.url=jdbc:h2:mem:test; 
DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;
spring.datasource.platform=h2
spring.datasource.username = sa
spring.datasource.password =
spring.datasource.driverClassName = org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.generate-ddl=true

My test case;

HotelEntity hotelEntity = new HotelEntity(1, "Name", "Password", "MobileNumber", "email");
hotelDao.save(hotelEntity);
System.out.println("Hotel Dao--");
List<HotelEntity> hotelEntities = hotelDao.findAll();
System.out.println(hotelEntities.size());

It print the list size is 1 but when i run test case again like this

List<HotelEntity> hotelEntities = hotelDao.findAll();
System.out.println(hotelEntities.size());

It print the list size is 0

buræquete
  • 14,226
  • 4
  • 44
  • 89
Ravi Jangid
  • 291
  • 1
  • 4
  • 15

1 Answers1

2

The problem is that during tests, any data you create will not be committed without proper transactional definition. My suggestions are;

  • Separate test h2 db from production h2 db, very dangerous to use same for both. You can use jdbc:h2:mem:test for testing, and jdbc:h2:mem:main for the production db for example.

  • Add spring.jpa.hibernate.ddl-auto=update for production db configuration, and spring.jpa.hibernate.ddl-auto=create-drop for test. Since you don't want to keep test db persisted.

  • If you are trying to commit data from test logic, you'd need to check this question

Also to be able to access h2 between sessions, you'd need to use an extra option, namely AUTO_RECONNECT, can you add them to your url?

spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE
buræquete
  • 14,226
  • 4
  • 44
  • 89