Java.lang.ClassCastException:java.lang.Long cannot is cast to Java.lang.Integer

Source: Internet
Author: User

Hibernate query result Bar number set

Original wording:

Integer count =  (integer) session.createquery (HQL). Uniqueresult ();

Error: Java.lang.ClassCastException:java.lang.Long cannot is cast to Java.lang.Integer

Reason:

After upgrading from Hibernate 3.0.x/3.1.x to the latest version 3.2, many of the 3.2 SQL functions such as COUNT (), the unique return value of sum () have changed from integer to Long, and if the code is not upgraded, Will get a classcastexception.
This change is primarily for JPA compatibility and can be found in the latest documentation for hibernate.org.

Solution:

1.hibernate is a solution in particular. When using Hibernate's query function for the value of count (), sum (), and so on ( Note: Must be only returned with a unique value and is available for number format ) uniqueresult () of query can be called; This method returns the object, simply converting it to the number type and then calling. Intvalue ().

For example:

Integer count =  ((number) Session.createquery (HQL). Uniqueresult ()). Intvalue ();

2. You can convert long to a string and then convert the string to integer;

Long i = (long) session.createquery (HQL). Uniqueresult (); Integer IInew Integer (string.valueof (i));

These two solutions can solve such problems ~

Java.lang.ClassCastException:java.lang.Long cannot is cast to Java.lang.Integer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.