JPA 本机查询 returns Double 或 BigDecimal
JPA native query returns Double or BigDecimal
我有下面的简单代码:
@PersistenceContext(name = "mycontext")
private EntityManager entityManager;
public void getAggregatePower() {
String sqlString = "SELECT SUM(power) FROM mytable";
Object singleResult = entityManager.createNativeQuery(sqlString).getSingleResult();
System.out.println(singleResult.getClass().getName());
}
当我在真实环境中 运行 时,打印指令打印 java.math.BigDecimal
。但是当我在我的单元测试环境中 运行 时,打印指令打印 java.lang.Double
.
在这两种情况下,我都使用 WildFly 9 服务器和 Postgresql 9.4 数据库。我还使用 Arquillian 进行单元测试。对我来说,唯一明显的区别是数据库中的记录数。
mytable
table 中的 power
列是 numeric(10,3)
.
我想避免丑陋的代码,例如:
if (singleResult instance of Double) {
...
} else if (singleResult instance of BigDecimal) {
...
}
有没有办法始终拥有相同的实例,无论我的 运行ning 环境如何?
BigDecimal
和 Double
都扩展了 Number
,因此您可以:
Number singleResult = ((Number) entityManager.createNativeQuery(sqlString).getSingleResult());
double resultAsDouble = singleResult.doubleValue();
BigDecimal resultAsBigDecimal = new BigDecimal(singleResult.toString());
如果您想要基本类型,请使用 resultAsDouble
,但不关心保留精确精度,否则请使用 resultAsBigDecimal
。
你可以这样做
String sql = "SELECT SUM(power) FROM mytable";
Query q = em.createNativeQuery(sql);
BigDecimal result = (BigDecimal)q.getSingleResult();
我有下面的简单代码:
@PersistenceContext(name = "mycontext")
private EntityManager entityManager;
public void getAggregatePower() {
String sqlString = "SELECT SUM(power) FROM mytable";
Object singleResult = entityManager.createNativeQuery(sqlString).getSingleResult();
System.out.println(singleResult.getClass().getName());
}
当我在真实环境中 运行 时,打印指令打印 java.math.BigDecimal
。但是当我在我的单元测试环境中 运行 时,打印指令打印 java.lang.Double
.
在这两种情况下,我都使用 WildFly 9 服务器和 Postgresql 9.4 数据库。我还使用 Arquillian 进行单元测试。对我来说,唯一明显的区别是数据库中的记录数。
mytable
table 中的 power
列是 numeric(10,3)
.
我想避免丑陋的代码,例如:
if (singleResult instance of Double) {
...
} else if (singleResult instance of BigDecimal) {
...
}
有没有办法始终拥有相同的实例,无论我的 运行ning 环境如何?
BigDecimal
和 Double
都扩展了 Number
,因此您可以:
Number singleResult = ((Number) entityManager.createNativeQuery(sqlString).getSingleResult());
double resultAsDouble = singleResult.doubleValue();
BigDecimal resultAsBigDecimal = new BigDecimal(singleResult.toString());
如果您想要基本类型,请使用 resultAsDouble
,但不关心保留精确精度,否则请使用 resultAsBigDecimal
。
你可以这样做
String sql = "SELECT SUM(power) FROM mytable";
Query q = em.createNativeQuery(sql);
BigDecimal result = (BigDecimal)q.getSingleResult();