SWEE
SWEE

Reputation: 467

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Even I'm casting Object into int, but this exception occur...

Actually my Hibernate-JPA method was return Object then I'm converting that Object into int...

Here is my Hibernate code:

@Transactional
public Object getAttendanceList(User user){

    Query query = entityManager.createQuery("select Count(ad) from AttendanceDemo ad inner join ad.attendee at  where at.user=:user",
            Long.class);
    query.setParameter("user", user);
    return query.getSingleResult();
}

Now I'm converting this Object as int:

int k = (Integer) userService.getAttendanceList(currentUser);

I'm converting Object to Integer.

Upvotes: 32

Views: 146476

Answers (4)

Mr Etineh
Mr Etineh

Reputation: 1

Just change the long to Number Remember your database is Number not int or long.

Upvotes: 0

Yehouda
Yehouda

Reputation: 122

You can do like that :

int k = Math.toIntExact((Long) userService.getAttendanceList(currentUser));

Upvotes: 0

Jeroen Kransen
Jeroen Kransen

Reputation: 1471

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

Upvotes: 6

fge
fge

Reputation: 121830

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

Upvotes: 73

Related Questions