JPA native query returns Double or BigDecimal

柔情痞子 提交于 2019-12-07 17:40:42

问题


I have the simple code below:

@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());

}

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 ?


回答1:


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()); 

Use resultAsDouble if you want the primitive type, but don't care about preserving the exact precision, use resultAsBigDecimal otherwise.




回答2:


You may do this

String sql = "SELECT SUM(power) FROM mytable";
Query q = em.createNativeQuery(sql);
BigDecimal result = (BigDecimal)q.getSingleResult();


来源:https://stackoverflow.com/questions/34786148/jpa-native-query-returns-double-or-bigdecimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!