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
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
Service Class
ACTION: GET
URI:
http://localhost:4001/incidencia
ERROR:
You should use the @Enumerated(EnumType.STRING) annotation, this will use the literal value as String. Here is an example:
Here you can get more information: https://tomee.apache.org/examples-trunk/jpa-enumerated/