How to silently truncate strings while storing them when they are longer than the column length definition?

前端 未结 12 1365
梦谈多话
梦谈多话 2020-12-24 06:17

I have a web app, using EclipseLink and MySQL for storing data. Some of these data are strings, ie varchars in the DB. In the code of entities, the strings have attributes

12条回答
  •  春和景丽
    2020-12-24 06:47

    There was already answer mentioned Converters, but I want to add more details. My answer also assumes Converters from JPA, not EclipseLink specific.

    At first create this class - special type converter which responsibility will be to truncate value at the persistence moment:

    import javax.persistence.AttributeConverter;
    import javax.persistence.Convert;
    
    @Convert
    public class TruncatedStringConverter implements AttributeConverter {
      private static final int LIMIT = 999;
    
      @Override
      public String convertToDatabaseColumn(String attribute) {
        if (attribute == null) {
          return null;
        } else if (attribute.length() > LIMIT) {
          return attribute.substring(0, LIMIT);
        } else {
          return attribute;
        }
      }
    
      @Override
      public String convertToEntityAttribute(String dbData) {
        return dbData;
      }
    }
    

    Then you can use it in your entities like this:

    @Entity(name = "PersonTable")
    public class MyEntity {
        
        @Convert(converter = TruncatedStringConverter.class)
        private String veryLongValueThatNeedToBeTruncated;
     
        //...
    }
    

    Related article about JPA Converters: http://www.baeldung.com/jpa-attribute-converters

提交回复
热议问题