skip to Main Content

I want to store an entity in Postgres with this schema

CREATE TABLE IF NOT EXISTS Ingredient
(
    id   VARCHAR(4)  NOT NULL PRIMARY KEY,
    name VARCHAR(25) NOT NULL,
    type VARCHAR(10) NOT NULL
);

This is the Java model

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PUBLIC, force = true)
public class Ingredient {
    @Id
    private final String id;
    private final String name;

    private final Type type;

    public enum Type {
        WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
    }
}

Here is the code

@Profile("!prod")
@Configuration
public class DevelopmentConfig {
    @Bean
    public CommandLineRunner dataLoader(
            IngredientRepository ingredientRepo,
    ) {
        return args -> {
            Ingredient flourTortilla = new Ingredient(
                    "FLTO", "Flour Tortilla", Type.WRAP);
            ingredientRepo.save(flourTortilla);
            
        };
    }
}

I receive this error – Caused by: org.hibernate.exception.DataException: Could not extract column [3] from JDBC ResultSet [Bad value for type byte : WRAP]

**Caused by: org.postgresql.util.PSQLException: Bad value for type byte : WRAP
**

Any advice is appriciated.

I have tried research this error but no answer was found, I have tried to define the column data type but it still no worked

2

Answers


  1. The most probable issue is that Spring, by default, stores Enums using their ordinal value (numeric) rather than their String value. You could attempt the following:

    private final String name;
    
    @Enumerated(EnumType.STRING)
    private final Type type;
    
    Login or Signup to reply.
  2. Hibernate is trying to convert the enum to a byte type by default, but the value of the enum is a string, not a byte, so you need to specify that you want the enum to be persisted as a String, using @Enumerated:

    @Data
    @Entity
    @AllArgsConstructor
    @NoArgsConstructor(access = AccessLevel.PUBLIC, force = true)
    public class Ingredient {
        @Id
        private final String id;
        private final String name;
    
        @Enumerated(EnumType.STRING)
        private final Type type;
    
        public enum Type {
            WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
        }
    }
    

    Read more: https://thorben-janssen.com/hibernate-enum-mappings/

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