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

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

    If you want to do this on a field-by-field basis rather than globally, then you might be able to make a custom type mapping that truncates the value to the given length before inserting it into the table. Then you can attach the converter to the entity by an annotation like:

    @Converter(name="myConverter", class="com.example.MyConverter")
    

    and to the relevant fields via:

    @Convert("myConverter")
    

    This is really meant for supporting custom SQL types, but it might work for normal varchar type fields as well. Here is a tutorial on making one of these converters.

提交回复
热议问题