JPA本机查询返回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
表中的power
列是numeric(10,3)
.
When I run this in a real environment, the print instructions prints java.math.BigDecimal
. But when I run this in my unit tests environment, the print instructions prints java.lang.Double
.
In both cases I use a WildFly 9 server and a Postgresql 9.4 database. I also use Arquillian for unit tests. For me, the only noticeable difference is the number of records in database.
The power
column in mytable
table is a numeric(10,3)
.
我想避免使用丑陋的代码,例如:
I would like to avoid ugly code such as:
if (singleResult instance of Double) {
...
} else if (singleResult instance of BigDecimal) {
...
}
无论我的运行环境如何,都可以始终拥有相同的实例吗?
Is there a way to always have the same instance no matter my running environment ?
推荐答案
BigDecimal
和Double
都扩展了Number
,因此您可以执行以下操作:
Both BigDecimal
and Double
extend Number
, so you can do:
Number singleResult = ((Number) entityManager.createNativeQuery(sqlString).getSingleResult());
double resultAsDouble = singleResult.doubleValue();
BigDecimal resultAsBigDecimal = new BigDecimal(singleResult.toString());
如果要使用基本类型,请使用resultAsDouble
,但不关心保留确切的精度,否则请使用resultAsBigDecimal
.
Use resultAsDouble
if you want the primitive type, but don't care about preserving the exact precision, use resultAsBigDecimal
otherwise.
这篇关于JPA本机查询返回Double或BigDecimal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!