@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {HibernateConfigTest.class})
@Transactional
@Sql(scripts = {"api_routes.sql",
"profile.sql",
"status.sql",
"user.sql",
"game_token.sql",
"game.sql",
"message.sql"},
config = @SqlConfig(transactionMode = ISOLATED),
executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "delete_data.sql",
executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public class GameDaoTest {
@Autowired
private GameDao gameDao;
@Test
public void getGetRecentGames() {
Game game = null;
for (int i = 0; i < 1000; i++) {
game = new Game(i + 1000);
game.setStartedAt(DateUtils.getCurrentUTCDate());
gameDao.save("game", game);
}
List<Game> recentGames = gameDao.getRecentGames(1000);
assertNotNull(recentGames);
assertEquals(1000, recentGames.size());
}
}
当我到达List<Game> recentGames = gameDao.getRecentGames(1000);
行时,hibernate打印出所有的insert语句。不幸的是,当检索到游戏时,我检索的所有游戏都没有被检索到。有没有办法检索那些游戏?也许更好的问题是如何将这些插入放在自己的事务中,以便后续方法保持这些插入?
这是GameDao扩展的AbstractDao:
public class AbstractDao {
@PersistenceContext
protected EntityManager entityManager;
protected Session getSession() {
return entityManager.unwrap(Session.class);
}
public void save(Object entity) {
getSession().save(entity);
}
public void save(String entityName, Object entity) {
getSession().save(entityName, entity);
}
public void persist(Object entity) {
getSession().persist(entity);
}
}
persist方法抛出了一些我不熟悉的分离实体的异常。
答案 0 :(得分:1)
在致电flush
之前,请尝试在会话中致电getRecentGames
。如果该方法正在执行自定义查询,而不是使用Hibernate的一种会话方法,那么它将直接针对数据库 - 但由于您的save
还没有与底层数据库同步,数据不存在。只要Hibernate可以看到数据,您实际上并不需要进行真正的提交。
for (int i = 0; i < 1000; i++) {
game = new Game(i + 1000);
game.setStartedAt(DateUtils.getCurrentUTCDate());
gameDao.save("game", game);
}
gameDao.flush(); // calls getSession().flush()
List<Game> recentGames = gameDao.getRecentGames(1000);
// call assert methods as needed