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

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

    One can truncate a string according to the JPA annotations in the setter for the corresponding field:

    public void setX(String x) {
        try {
            int size = getClass().getDeclaredField("x").getAnnotation(Column.class).length();
            int inLength = x.length();
            if (inLength>size)
            {
                x = x.substring(0, size);
            }
        } catch (NoSuchFieldException ex) {
        } catch (SecurityException ex) {
        }
        this.x = x;
    }
    

    The annotation itself should look like:

    @Column(name = "x", length=100)
    private String x;
    

    (Based on https://stackoverflow.com/a/1946901/16673)

    The annotations can be recreated from the database if the database changes, as hinted in the comment to https://stackoverflow.com/a/7648243/16673

提交回复
热议问题