java.math.BigInteger cannot be cast to java.lang.Long错误的解决方案

场景

mysql数据库中

字段为`authority_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '权限ID',

问题


public interface BmRoleAuthorityRepository extends JpaRepository<BmRoleAuthority, Long>{

@Query(value = "SELECT authority_id FROM bm_role_authority where role_id = ?1", nativeQuery = true)
List<Long> getAllAuthorityIdByRoleId(Long roleId);

直接执行,获取到的List<Long>是

之后我想循环authorityIdList

for (Long authorityId : authorityIdList) {

 

结果报错:

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

解决方案

没有看到有什么特别好的方法,只能将BigInterger的List先转换为String,然后再转换为Long List


List<Long> authorityIdList = bmRoleAuthorityRepository.getAllAuthorityIdByRoleId(roleId);

if(authorityIdList == null || authorityIdList.isEmpty()) {
   authorityIdList = new ArrayList<>();
}
String idArray = JSONArray.toJSONString(authorityIdList);

之后再处理这个String,将其转换为Long list


// [1,2,3] convert to String[]
String[] split = StringUtils.split(StringUtils.substring(allAuthorityIdByRoleId, 1,
        allAuthorityIdByRoleId.length() - 1), ",");
// guava 将String[] convert to Long[]
authorityIdList.addAll(Lists.transform(Arrays.asList(split), Longs.stringConverter()));

参考:

关于java.math.BigInteger cannot be cast to java.lang.Integer小方法

Decompose a String into Array of Long or List of Long without Loop in JAVA

发布了442 篇原创文章 · 获赞 222 · 访问量 115万+

猜你喜欢

转载自blog.csdn.net/u013905744/article/details/100895772