lombok导致的IndexOutOfBoundsException

一、问题描述

ERROR 25152 --- [1.190-81-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:

### Error querying database. Cause: java.lang.IndexOutOfBoundsException: Index: 2, Size: 2

### The error may exist in file [E:\mycode\honeywell-iot-regain\target\classes\mapper\WarnMapper.xml]

### The error may involve com.honeywell.iot.mapper.WarnMapper.countByEveryMonth

### The error occurred while handling results

### SQL: SELECT DATE_FORMAT(create_time, '%m') AS month, COUNT(*) AS monthcount FROM warn WHERE create_time LIKE '2024%' GROUP BY MONTH(create_time);

### Cause: java.lang.IndexOutOfBoundsException: Index: 2, Size: 2] with root cause

java.lang.IndexOutOfBoundsException: Index: 2, Size: 2

at java.util.ArrayList.rangeCheck(ArrayList.java:657) ~[na:1.8.0_221]

at java.util.ArrayList.get(ArrayList.java:433) ~[na:1.8.0_221]

lombok导致的IndexOutOfBoundsException_第1张图片

二、问题解决

  • 看到报错信息,显示IndexOutOfBoundsException,即索引越界异常。感到很纳闷,再结合sql语句的出现,最初以为是sql语句查询到多条结果,只用了一个对象而没有用集合接收。

  • 确认是在用集合接收后,怀疑是sql语句写错了,将sql语句放到Navicat运行正常。至此,从报错信息处好像得不到什么有用信息。

  • 又想到之前是正常的,因为刚刚改动了某些东西才报错的。 于是排查改过的代码,发现在实体CountPojo类上添加了lombok的满参构造@AllArgsConstructor注解。

  • 瞬间灵光一现,有一些想法出现了。

  • lombok在添加了@Data注解后,默认添加一个无参构造的方法,而在添加了@AllArgsConstructor满参构造方法后,会将无参构造删除后,再添加满参构造方法。

  • 而sql查询结果的封装,需要基于无参构造来执行。 所以,只需添加一个lombok无参构造@NoArgsConstructor注解,问题即得到解决。

三、总结

在使用lombok注解时,最好是@AllArgsConstructor和@NoArgsConstructor一起使用。

lombok导致的IndexOutOfBoundsException_第2张图片

你可能感兴趣的:(java,bug)