java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long

Below example, the jdbcTemplate.queryForList returns an object of Integer and we try to convert it into a Long directly:


	public List<Customer> findAll() {

        String sql = "SELECT * FROM CUSTOMER";

        List<Customer> customers = new ArrayList<>();

        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);

        for (Map row : rows) {
            Customer obj = new Customer();

            obj.setID(((Long) row.get("ID"))); // the object is an Integer
            obj.setName((String) row.get("NAME"));

            customers.add(obj);
        }

        return customers;
    }

Output


Caused by: java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long 
(java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap')
	at com.mkyong.misc.CustomerRepository.findAll(CustomerRepository.java:73)
	at com.mkyong.misc.CustomerRepository$$FastClassBySpringCGLIB$$7fc6ff36.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
	at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
	at com.mkyong.misc.CustomerRepository$$EnhancerBySpringCGLIB$$f96f7027.findAll(<generated>)
	at com.mkyong.StartApplication.startCustomerApp(StartApplication.java:103)
	at com.mkyong.StartApplication.run(StartApplication.java:72)
	at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813)

Solution

To solve it, convert it back to the original Integer and cast it to Long


	obj.setID(((Integer) row.get("ID")).longValue());
	//obj.setID(((Long) row.get("ID")));

Java basic:


	Integer num = 1;

	Long numInLong = num.longValue();	 // Integer to Long

	Long numInLong2 = Long.valueOf(num); // Integer to Long

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
salaheddine Recent comment authors
newest oldest most voted
salaheddine
Guest
salaheddine

Hi,
Casting to Integer knowing that the ID is Long can change the value of ID if it’s value is superior to 2^31 – 1