skip to Main Content

How can I properly map an ENUM data type from my database to my Spring Data JPA entity using Hibernate?

I have an ENUM type defined in my database schema, and I’m using Spring Data JPA with Hibernate for my Java application. I want to map this ENUM type to an attribute in my JPA entity class, but I’m encountering issues with data integrity when fetching data from the database.

Here’s my ENUM definition in the database:

ENUM('EQUIPOS', 'CUENTAS', 'WIFI', 'INTERNET', 'SOFTWARE')

And here’s how I’ve defined the corresponding Java enum:

public enum TipoEnum {
    EQUIPOS,
    CUENTAS,
    WIFI,
    INTERNET,
    SOFTWARE
}

My JPA entity class looks like this:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    // How do I properly map this ENUM type to my database column?
    private TipoEnum tipo;

    // Getters and setters...
}

When I try to fetch data from the database using Spring Data JPA repositories, I’m getting errors related to data integrity violations. It seems like Hibernate is trying to map the ENUM values incorrectly.

How can I properly map the ENUM type from my database to my JPA entity class using Spring Data JPA and Hibernate? Are there any specific annotations or configurations that I need to use to ensure the correct mapping and prevent data integrity issues?

Identified that the error Value ‘EQUIPOS’ is outside of valid range for type java.lang.Byte is occurring due to the ENUM data type in the database.
Created a Java enum TipoEnum to represent the ENUM values present in the database.
Verified that the ENUM values in the database are ‘EQUIPOS’, ‘CUENTAS’, ‘WIFI’, ‘INTERNET’, ‘SOFTWARE’.
Ensured that the TipoEnum enum in Java matches the ENUM values in the database.
Investigated the error message to understand the root cause.

2

Answers


  1. Chosen as BEST ANSWER

    I will add the rest of the code, just in case someone knows the solution:

    mySQL datatype: ENUM

    Java dataType ENUM

    All values match.

    Entity Class

    @Entity
    @Table(name = "incidencias", schema = "tic_incidencias", catalog = "")
    public class IncidenciasEntity {
        @Id
        @Column(name = "num", nullable = false)
        private int num;
        @Enumerated(EnumType.STRING)
        @Column(name = "tipo", nullable = false)
        private TipoEnum  tipo;
        @ManyToOne
        @JoinColumn(name = "subtipo_id", foreignKey = @ForeignKey(name = "FK_INCIDENCIA_INCIDENCIASUBTIPO"))
        private IncidenciasSubtiposEntity subtipoId;
        @Basic
        @Column(name = "fecha_creacion", nullable = false)
        private Timestamp fechaCreacion;
        @Basic
        @Column(name = "fecha_cierre", nullable = true)
        private Timestamp fechaCierre;
        @Basic
        @Column(name = "descripcion", nullable = false, length = -1)
        private String descripcion;
        @Enumerated(EnumType.STRING)
        @Column(name = "estado", nullable = false)
        private EstadoEnum estado;
        @Basic
        @Column(name = "adjunto_url", nullable = true, length = -1)
        private String adjuntoUrl;
        @ManyToOne
        @JoinColumn(name = "creador_id", foreignKey = @ForeignKey(name = "FK_PERSONALCREADOR_INCIDENCIA"))
        private PersonalEntity creadorId;
        @ManyToOne
        @JoinColumn(name = "responsable_id", foreignKey = @ForeignKey(name = "FK_PERSONALRESPONSABLE_INCIDENCIA"))
        private PersonalEntity responsableId;
        @ManyToOne
        @JoinColumn(name = "equipo_id", foreignKey = @ForeignKey(name = "FK_EQUIPO_INCIDENCIA"))
        private EquiposEntity equipoId;
        @Enumerated(EnumType.STRING)
        @Column(name = "prioridad", nullable = false)
        private PrioridadEnum prioridad;
    
        public int getNum() {
            return num;
        }
    
        public void setNum(int num) {
            this.num = num;
        }
    
        public TipoEnum getTipo() {
            return tipo;
        }
    
        public void setTipo(TipoEnum tipo) {
            this.tipo = tipo;
        }
    
        public IncidenciasSubtiposEntity getSubtipoId() {
            return subtipoId;
        }
    
        public void setSubtipoId(IncidenciasSubtiposEntity subtipoId) {
            this.subtipoId = subtipoId;
        }
    
        public Timestamp getFechaCreacion() {
            return fechaCreacion;
        }
    
        public void setFechaCreacion(Timestamp fechaCreacion) {
            this.fechaCreacion = fechaCreacion;
        }
    
        public Timestamp getFechaCierre() {
            return fechaCierre;
        }
    
        public void setFechaCierre(Timestamp fechaCierre) {
            this.fechaCierre = fechaCierre;
        }
    
        public String getDescripcion() {
            return descripcion;
        }
    
        public void setDescripcion(String descripcion) {
            this.descripcion = descripcion;
        }
    
        public EstadoEnum getEstado() {
            return estado;
        }
    
        public void setEstado(EstadoEnum estado) {
            this.estado = estado;
        }
    
        public String getAdjuntoUrl() {
            return adjuntoUrl;
        }
    
        public void setAdjuntoUrl(String adjuntoUrl) {
            this.adjuntoUrl = adjuntoUrl;
        }
    
        public PersonalEntity getCreadorId() {
            return creadorId;
        }
    
        public void setCreadorId(PersonalEntity creadorId) {
            this.creadorId = creadorId;
        }
    
        public PersonalEntity getResponsableId() {
            return responsableId;
        }
    
        public void setResponsableId(PersonalEntity responsableId) {
            this.responsableId = responsableId;
        }
    
        public EquiposEntity getEquipoId() {
            return equipoId;
        }
    
        public void setEquipoId(EquiposEntity equipoId) {
            this.equipoId = equipoId;
        }
    
        public PrioridadEnum getPrioridad() {
            return prioridad;
        }
    
        public void setPrioridad(PrioridadEnum prioridad) {
            this.prioridad = prioridad;
        }
    }
    

    Service Class

        @Repository
        public class IncidenciaService {
        
            @Autowired
             IIncidenciasRepository incidenciasRepository;
        
            public ArrayList<IncidenciasEntity> getIncidencias() {
                return(ArrayList<IncidenciasEntity>) incidenciasRepository.findAll();
            }
        
            public IncidenciasEntity saveIncidencia(IncidenciasEntity incidencia) {
                return incidenciasRepository.save(incidencia);
            }
        
            public Optional<IncidenciasEntity> getById(Integer id) {
                return incidenciasRepository.findById(id);
            }
        
            public IncidenciasEntity updateById(IncidenciasEntity request, Integer id) {
                IncidenciasEntity incidencia = incidenciasRepository.findById(id).orElse(null);
                if (incidencia != null) {
                   /* incidencia.setTipo(request.getTipo());*/
                    incidencia.setSubtipoId(request.getSubtipoId());
                    incidencia.setFechaCreacion(request.getFechaCreacion());
                    incidencia.setFechaCierre(request.getFechaCierre());
                    incidencia.setDescripcion(request.getDescripcion());
                    incidencia.setEstado(request.getEstado());
                    incidencia.setAdjuntoUrl(request.getAdjuntoUrl());
                    incidencia.setCreadorId(request.getCreadorId());
                    incidencia.setResponsableId(request.getResponsableId());
                    incidencia.setEquipoId(request.getEquipoId());
                    incidencia.setPrioridad(request.getPrioridad());
                    incidenciasRepository.save(incidencia);
                }
                return incidencia;
            }
        
            public boolean deleteIncidencia(Integer id) {
                try {
                    incidenciasRepository.deleteById(id);
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }
        }
    
    
    Controller Class:
    
    
    
    @RestController
    @RequestMapping("/aula") //End point para buscar por aulas
    public class AulaController {
    
        @Autowired
        private AulaService aulaService;
    
        @GetMapping
        public ArrayList<AulasEntity> getAulas() {
            return this.aulaService.getAulas();
        }
    
        @PostMapping(path = "/post")
        public AulasEntity saveAula(@RequestBody AulasEntity aula) {
            return this.aulaService.saveAula(aula);
        }
    
        @GetMapping(path = "/{id}")
        public Optional<AulasEntity> getAulaById(@PathVariable Integer id) {
            return this.aulaService.getById(id);
        }
    
        @PutMapping("/put/{id}")
        public AulasEntity updateAulaById(@RequestBody AulasEntity request, @PathVariable Integer id) {
            return this.aulaService.updateById(request, id);
        }
    
        @DeleteMapping(path = "/del{id}")
    
        public String deleteById(@PathVariable("id") Integer id) {
            boolean ok = this.aulaService.deleteAula(id);
            if (ok) {
                return "Aula con id " + id + " borrado.";
            } else {
                return "Error, no se encuentra el aula con id " + id + ".";
            }
        }
    
    }
    

    ACTION: GET

    URI:

    http://localhost:4001/incidencia

    ERROR:

    2024-02-09T06:22:05.618+01:00 ERROR 7040 --- [nio-4001-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.DataIntegrityViolationException: Could not extract column [4] from JDBC ResultSet [Value 'EQUIPOS' is outside of valid range for type java.lang.Byte] [n/a]; SQL [n/a]] with root cause
    
    com.mysql.cj.exceptions.NumberOutOfRange: Value 'EQUIPOS' is outside of valid range for type java.lang.Byte
    

  2. You should use the @Enumerated(EnumType.STRING) annotation, this will use the literal value as String. Here is an example:

    @Enumerated(EnumType.STRING)
    private TipoEnum tipo;
    

    Here you can get more information: https://tomee.apache.org/examples-trunk/jpa-enumerated/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search