这让我很困惑。我只是弄清楚发生了什么,但我会提出并回答我自己的文档问题,以防它帮助其他人。
我有以下代码:
我的类.java
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;
}
警告 现在这里是答案的来源 ans 使下面的测试无效,所以请对它持保留态度。我以为第一个断言会通过,而第二个断言会失败。事实并非如此:第一个在某些情况下最终失败了。
MyClassTest.java
@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);
}
最佳答案
回答:不同的数据库可能会返回不同的标量类型。
我的问题是使用 @RunWith(Parameterized.class)
的结果针对 2 个不同数据库(Oracle 和 MS SQL Server)运行的单元测试。它可能与列的定义方式有关(我没有研究过),但基本要点是您可能无法依赖 JPA 在数据库之间切换时将转换为的特定对象类型。为了安全起见,您可能只想假设 List<? extends Number>
.
关于java - 为什么 EntityManager createNativeQuery 列表有时返回 BigDecimal 而有时返回 Integer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12429233/