I have a Junit test case for testing a method which require some initial data. The data required is not part of the current schema used by my hibernate project. So I cannot use model object to create that insert data. Is there any way to run sql scripts before and after running junit test ?
The Non Hibernate way is the following
Process p = Runtime.getRuntime().exec("psql -U user -d db -h host -f file.sql");
How to handle this using hibernate ?
I solved this by running native sql query using the hibernate api
Query persistableQuery = entityManager.createNativeQuery("QUERY");
persistableQuery.executeUpdate();
The @Sql annotation is my first option. Haven't tried it, but since you are using Spring, you can also use ScriptUtils in your @Before method:
Connection connection = dataSource.getConnection();
ScriptUtils.executeSqlScript(connection, new ClassPathResource("test_db.sql"));
还有一个名为dbunit的好库,它允许在junit测试之前和之后将数据库设置为已知状态。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.