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

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

    You can use a Descriptor PreInsert/PreUpdate event for this, or possibly just use JPA PreInsert and PreUpdate events.

    Just check the size of the fields and truncate them in the event code.

    If required, you could get the field size from the descriptor's mapping's DatabaseField, or use Java reflection to get it from the annotation.

    It would probably be even better to just do the truncation in your set methods. Then you do not need to worry about events.

    You may also be able to truncate it on the database, check your MySQL settings, or possible use a trigger.

提交回复
热议问题