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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With