当它们长于列长度定义时,如何在存储字符串时静默截断字符串? [英] How to silently truncate strings while storing them when they are longer than the column length definition?

查看:281
本文介绍了当它们长于列长度定义时,如何在存储字符串时静默截断字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,使用EclipseLink和MySQL存储数据。
其中一些数据是字符串,即DB中的varchars。
在实体代码中,字符串具有如下属性:

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 like this:

@Column(name = "MODEL", nullable = true, length = 256)
private String model;

eclipseLink不会从代码中创建数据库,但长度与数据库中的varchar长度匹配。
当这样的字符串数据的长度大于length属性时,在调用javax.persistence.EntityTransaction.commit()期间会引发异常:

The database is not created by eclipseLink from the code, but the length matches the varchar length in the DB. When the length of such a string data is greater than the length attribute, an exception is raised during the call to javax.persistence.EntityTransaction.commit():

javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.1.0.v20100614-r7608): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'MODEL' at row 1

然后回滚事务。
虽然我知道这是默认行为,但这不是我想要的。
我希望数据被静默截断,以及要提交的事务。

Then the transaction is rolled back. While I understand that it is the default behaviour, this is not the one I want. I would like the data to be silently truncated, and the transaction to be committed.

我是否可以在不向每个子服务器添加对子字符串的调用的情况下执行此操作设置相关实体​​的字符串数据的方法?

Can I do this without adding a call to substring to each and every set method of string data for the concerned entities?

推荐答案

可以根据setter中的JPA注释截断字符串相应字段:

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;
}

注释本身应如下所示:

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

(基于 https://stackoverflow.com/a/1946901/16673

如果数据库发生变化,可以从数据库重新创建注释,如提示在 https://stackoverflow.com/a/7648243/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

这篇关于当它们长于列长度定义时,如何在存储字符串时静默截断字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆