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

前端 未结 12 1369
梦谈多话
梦谈多话 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:30

    Another option is to declare a constant and reference it everywhere you need that length starting with the @Column annotation itself.

    This constant can be then forwarded to a truncate function or a validation function that throw a preventive exception if the passed string is too long. This constant can also be re-used on some other layers such as a UI.

    For example:

    @Entity
    public class MyEntity {
        public static final int NAME_LENGTH=32;
    
        private Long id;
        private String name;
    
        @Id @GeneratedValue
        public Long getId() {
            return id;
        }
        protected void setId(Long id) {
            this.id = id;
        }
    
        @Column(length=NAME_LENGTH)
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = JpaUtil.truncate(name, NAME_LENGTH);
        }
    }
    
    public class JpaUtil {
        public static String truncate(String value, int length) {
            return value != null && value.length() > length ? value.substring(0, length) : value;
        }
    }
    

提交回复
热议问题