Search code examples
javahibernatespring-bootspring-data-jpatrim

How can I configure Spring Boot JPA Java Entities to automatically trim Strings from every CHAR column?


I'm shocked an answer for this hasn't been easier to find, but - how can I configure my Spring-Boot application's JPA Entities to ALL automatically trim EVERY String property?

I'm working with a legacy DB2 database, in which every value of every CHAR column is padded with trailing spaces by various applications beyond my control. There about 50 interconnected tables with many CHAR(N) columns, and I have to do countless transformations and comparisons with the data, and those transformations / comparisons NEVER work with trailing spaces. So I find myself calling trim() about a billion times in my code.

Overriding the Entity POJO classes' getter/setter methods feels disgusting, as there are hundreds, and because I just got rid of them all by using Lombok. Pleeeeaaase tell me there's a way to configure Spring/Hibernate to automatically trim trailing spaces from every CHAR(N) String column...

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@NoArgsConstructor
@Entity
@Table(name="MEASUREMENT_TYPE")
public class MeasurementType {
    @Id
    @Column(name="MSR_TYP_CD")
    private short measurementTypeCode;

    @Column(name="DES_TXT", columnDefinition = "CHAR", length = 5)
    private String description;
}

Solution

  • One solution would be to create a custom converter, something like this:

    @Converter
    public class CharConverter implements AttributeConverter<String, String> {
    
        @Override
        public String convertToDatabaseColumn(String value) {
            return value;
        }
    
        @Override
        public String convertToEntityAttribute(String value) {
            if (value == null) {
                return null;
            }
    
            return value.trim();
        }
    
    }
    

    And apply it in every CHAR column with:

    @Column(name="DES_TXT", columnDefinition = "CHAR", length = 5)
    @Convert(converter = CharConverter.class)
    private String description;