javaspring-boothibernatejpa

Receiving Data Too Long for column


I'm working with a Spring Boot application using JPA and Hibernate, and I'm trying to persist a field that is serialized as JSON using a custom @Converter. The field is mapped to a varchar(2000) column in MySQL.
DTO:

@XmlElement
private Object value;

Entity:

@Column(name = "value")
@Convert(converter = JpaConverterJson.class)
private Object value;

Converter:

@Component
@Converter
@Slf4j
public class JpaConverterJson implements AttributeConverter<Object, String> {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public String convertToDatabaseColumn(Object meta) {
        try {
            objectMapper.disable(SerializationFeature.WRAP_ROOT_VALUE);
            return objectMapper.writeValueAsString(meta);
        } catch (JsonProcessingException ex) {
            log.error("JsonProcessingException encoding Object into String: {}", ex.getMessage());
            return null;
        }
    }

    @Override
    public Object convertToEntityAttribute(String dbData) {
        try {
            return objectMapper.readValue(dbData, Object.class);
        } catch (IOException ex) {
            log.error("IOException decoding json from database: {}", ex.getMessage());
            return null;
        }
    }
}

Issue:

When I run a native SQL INSERT query, the data gets stored correctly.

But when I persist the entity using JPA, I get this error:

com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'value' at row 1

Why does Hibernate fail to persist the data when the native SQL works?


Solution

  • Before persisting the JSON string, Hibernate validates its length against the defined column size (e.g., VARCHAR(2000)). If the content exceeds this limit, it throws a Data too long for column exception. In contrast, native SQL operations may silently truncate the data or bypass length validation altogether.


    Use LONGTEXT to handle large JSON:

    @Column(name = "value", columnDefinition = "LONGTEXT")
    @Convert(converter = JpaConverterJson.class)
    private Object value;
    

    And update the column in MySQL:

    [LONGTEXT avoids size issues for large JSON data]

    ALTER TABLE your_table MODIFY COLUMN value LONGTEXT;
    

    I hope your problem is solved.