我想使用JavaFx,Spring Boot和Spring Data JPA以H2作为我的数据库来创建桌面应用程序。问题是我试图运行Junit在本地保存数据,但每次运行Junit时数据都会丢失。
我的application.properties
文件;
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
我的测试用例;
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());
它打印列表大小为1但是当我再次运行测试用例时这样
List<HotelEntity> hotelEntities = hotelDao.findAll();
System.out.println(hotelEntities.size());
它打印列表大小为0
问题是在测试期间,如果没有正确的事务定义,您创建的任何数据都不会被提交。我的建议是;
jdbc:h2:mem:test
进行测试,并使用jdbc:h2:mem:main
作为生产数据库。spring.jpa.hibernate.ddl-auto=update
,为测试添加spring.jpa.hibernate.ddl-auto=create-drop
。因为你不想保持测试数据库持久化。也是为了能够在会话之间访问h2
,你需要使用一个额外的选项,即AUTO_RECONNECT
,你可以将它们添加到你的网址吗?
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE