java - [java.lang.ArrayIndexOutOfBoundsException : Index 2 out of bounds for length 2]

标签 java spring spring-boot enums

我知道有人问过这个问题 here但我找不到解决方案。所以answer在该问题中解释问题:

The exception happens at EnumJavaTypeDescriptor.fromOrdinal. So my guess is that your role_id value in the database column is 2.

But there are only two values in the UserType enum: ADMIN and USER. ADMIN's ordinal is 0, and USER's ordinal is 1. So if your row contains 2 in the user_type column, it's an invalid ordinal for the UserType enum.

在数据库中,我有两个值 1 和 2 代表两个字符串“black”和“white”,所以我无法将它们从 1 和 2 更改为 0 和 1。所以我应该在我的 java 代码中处理它,所以我尝试了这个但我不断收到相同的错误

public enum TypeColor {
    black(1),
    white(2);

    private int val;

    private TypeColor(int val) {
        this.val = val;
    }
}

更新

这是使用该枚举的实体

@Entity
@Table(name = "BOOKS")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Book implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id")
    private Long id;
   
   private TypeColor typeColor; 

    //other attributes, getters, setters
    
}

在 Controller 中,当我尝试获取所有书籍时,我收到了该错误(在标题中)

@GetMapping("/books")
    public ResponseEntity<List<Book>> getAllBooks(@org.springdoc.api.annotations.ParameterObject Pageable pageable) {
        log.debug("REST request to get a page of Books");
        Page<Rdv> page = bookRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

最佳答案

要将 int 转换为枚举(其中该 int 不是枚举常量的ordinal()),您需要一个查找函数。您已经将整数值分配给常量,因此剩下的就是查找本身:

public enum TypeColor {
    black(1),
    white(2);

    private int val;

    private TypeColor(int val) {
        this.val = val;
    }

    static TypeColor lookup(int v) {
        for(TypeColor t:values()) {
            if(t.val == v) {
                return t;
            }
        }
        return null; //or throw an Exception
    }
}

关于java - [java.lang.ArrayIndexOutOfBoundsException : Index 2 out of bounds for length 2],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72366094/

相关文章:

angularjs - 使用 AngularJS 通过自定义登录进行 Spring Security 身份验证

java - 创建 Spring 数据源以连接到 Google Cloud SQL

spring-boot - Ehcache 3 和 Spring Boot Admin 统计信息

java - Spring Boot 正在缓存结果而不启用它

java - 用反斜杠转义字符

java - 为 Maven 构建的 Web 应用程序指定运行时配置参数

java - 如何访问位于jar的 'META-INF/resources'文件夹中的jsp页面中的Exception对象?

Java Swing 自定义布局问题

java - 身份验证在 Spring 中不起作用

java - Spring Boot 中的 SSL 证书