8

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;
}
SnoopDougg
  • 1,467
  • 2
  • 19
  • 35
  • Some people have already dealt with this : https://stackoverflow.com/questions/21902919/how-to-trim-white-spaces-from-char-fields-pojo-using-hibernate-and-legacy-databa/25658328#25658328 – Olivier Depriester May 08 '20 at 21:05
  • Not sure if this is good idea, especially in case of huge legacy system: could be 'constraint violation' error if there was foreign key or unique constant on field. – Alex Chernyshev May 08 '20 at 21:13

1 Answers1

11

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;
areus
  • 2,880
  • 2
  • 7
  • 17
  • Thanks!! I was hoping there was some kind of spring/hibernate configuration property I could set, but this is definitely way better than having to define setters/getters/post-construct methods. – SnoopDougg May 12 '20 at 01:42