What object type does Spring Hibernate Template execute method return for a counting query on Oracle?

后端 未结 4 822
不知归路
不知归路 2020-12-31 10:19

When run against and Oracle database, what is the runtime type of the object that the following Spring Hibernate Template (Spring 2.5 and Hibernate 3.3.2GA) code returns whe

相关标签:
4条回答
  • 2020-12-31 11:08

    Turns out that the ClassCastException may be due to a bug in the Hibernate standard query cache.

    Solution is to add a scalar to the query:

    String sql = "select count(*) as result from table";
    BigDecimal count = (BigDecimal) ht.execute(new HibernateCallback() {
        public Object doInHibernate(Session session)
                throws HibernateException {
            SQLQuery query = session.createSQLQuery(sql);
            // Add scalar to avoid bug in Hibernate query cache.
            query.addScalar("result", Hibernate.BIG_DECIMAL);
            return query.uniqueResult();
        }
    });
    

    References:

    • ClassCastException with SQLQuery and setCacheable(true)
    • Martin Schaaf's Blog: ClassCastException with SQLQuery and setCacheable(true)
    • Caching a raw sql count with Hibernate and EhCache
    • HHH-5163 Bug when applying a ResultTransformer on a cacheable projection based criteria
    • ClassCastException when Hibernate tries to cache results using ResultTransformer
    0 讨论(0)
  • 2020-12-31 11:11

    The class type of the object that hibernateTemplate.execute() returns is indeed BigDecimal. It turns out that the cause of the ClassCastException is the cast of the return value of method doInHibernate():

    (BigDecimal) query.uniqueResult();
    

    Corrected code:

     BigDecimal count = (BigDecimal) hibernateTemplate.execute(
       new HibernateCallback() { 
        public Object doInHibernate(Session session) throws HibernateException {
         SQLQuery query = session.createSQLQuery(sql);
         return query.uniqueResult();
        }});
     return count;
    
    0 讨论(0)
  • 2020-12-31 11:12

    How about

    long value = ((Number)query.uniqueResult()).longValue();
    return Long.valueOf(value);
    

    This would work for all subclasses of Number like Long, Double, Biginteger or BigDecimal.

    0 讨论(0)
  • 2020-12-31 11:13

    I think it returns type Long. I have used Long in my code. But if your BigDecimal works then even I want to know what is the return type :)

    0 讨论(0)
提交回复
热议问题