这令我感到困惑很多。我只是弄清楚发生了什么,但是我会问问题并回答我自己的问题,以备文件帮助别人。
我有以下代码:
public List<Integer>
getPersonIdsByPrograms(Collection<Integer> programIds, boolean getFirst) {
String sql = "SELECT p.PERSON_ID FROM PERSON p " +
"WHERE p.PROGRAM_ID in (?programIds)";
sql = sql.replaceAll("\\?programIds", StringUtils.join(programIds, ","));
Query query = entityManager.createNativeQuery(sql);
//EntityManager returns scalar values, in this case, BigDecimal
List<BigDecimal> queryResults = query.getResultList();
// !! This is the toggle that makes or breaks the tests !!
// !! !! UPDATE: Red herring. This had no impact. See answer for why !! !!
if (getFirst) {
Object firstObj = queryResults.get(0); //This makes the test pass!?!
//This is always true
System.out.println("Is firstObj a BigDecimal? Answer: "
+ (firstObj instanceof BigDecimal));
}
//Returns list of BigDecimal, so need to convert to Integer
List<Integer> result = Lists.transform(queryResults, new Function<BigDecimal, Integer>() {
public Integer apply(BigDecimal n) {
return Integer.valueOf(n.intValue());
}
});
return result;
}
警告 现在这里是答案的来源,使下面的测试无效,所以带上一粒盐。我想到第一个断言将要通过而第二个断言将失败。事实并非如此:在某些情况下,第一次失败了。
@Test
public void getPersonIdsByProgramsTest_BigDecimalOrInteger() {
ArrayList<Integer> programs = Lists.newArrayList(131,141,161,162,0,113,110,26,5,28,50,58,51,29,121,31,101,41,27);
List<?> personsByPrograms = userDao.getPersonIdsByPrograms(programs, true);
TestingUtils.assertNotNullOrEmpty(personsByPrograms);
Object shouldBeInteger = personsByPrograms.get(0);
assertTrue(shouldBeInteger instanceof Integer);
personsByPrograms = userDao.getPersonIdsByPrograms(programs, false);
TestingUtils.assertNotNullOrEmpty(personsByPrograms);
shouldBeInteger = personsByPrograms.get(0);
assertTrue(shouldBeInteger instanceof Integer);
}
答案 0 :(得分:1)
我的问题是使用针对2个不同数据库(Oracle和MS SQL Server)运行的@RunWith(Parameterized.class)
单元测试的结果。它可能与列的定义方式有关(我没有查看过),但基本要点是,您可能无法依赖JPA在数据库之间切换时将要转换的特定对象类型。为安全起见,您可能只想假设List<? extends Number>
。