Home > front end >  [java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2]
[java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2]

Time:05-25

I know this question has been asked here but I can't found a solution. So the answer in that question explain the problem :

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.

In the database I have two values 1 and 2 representing two strings "black" and "white" so I cannot change them from 1 and 2 to 0 and 1. So I should handle it in my java code so I tried this but I keep getting the same error

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

    private int val;

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

UPDATE

here is the entity that uses that enum

@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
    
}

in Controller when I try to get all books, I got that error (in the title)

@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());
    }

CodePudding user response:

To convert an int to an enum where that int is not the ordinal() of the enum constants, you need a lookup function. You already assigned the integer values to the constants, so all that is left is the lookup itself:

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
    }
}

CodePudding user response:

Well, I had to get documented more about enum world. If anyone having the same issue as me here is the solution it worked for me :

this link helped me a lot

TypeColor.java

public enum TypeColor {
    black("1"), //in database this field has a varchar as datatype 
    white("2");

    private String code;

    private TypeColor(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

So the missing part I needed is the following class that makes the mapping between the column in database and enum using JPA 2.1

TypeColorConverter.java

@Converter(autoApply = true)
public class TypeColorConverter implements AttributeConverter<TypeColor, String> {

    @Override
    public String convertToDatabaseColumn(TypeColor color) {
        if (color == null) {
            return null;
        }
        return color.getCode();
    }

    @Override
    public TypeColor convertToEntityAttribute(String code) {
        if (code == null) {
            return null;
        }

        return Stream
            .of(TypeColor.values())
            .filter(c -> c.getCode().equals(code))
            .findFirst()
            .orElseThrow(IllegalArgumentException::new);
    }
}
  • Related