Java – correctly handle long data in Hibernate

I received a problem that the data is too large in hibernate That's-

Whether it is possible to automatically truncate the data of all fields Or any other way to deal with this problem But I don't want to check the data length of all fields because I have more than a thousand fields

Solution

As far as I know, hibernate or MySQL can't automatically truncate strings without adding logic to deal with this The reason I believe such a thing doesn't exist is that I never want what I'm asked to insert into the database instead of what I really insert

I think your only choice is

>Change column definition Make it a bigger varchar field, maybe even a text field Just change the column definition to fix this problem in a few clicks and take the time to build a magic tool I suggest this! > I can see that you intercept setter in some way, and then adjust the size of the string if it is larger than the X length. This will be the fastest reason to process in your code If changing the database is not an option and you have thousands of fields, this will be my next choice. > Build a string util class that can resize strings

setText(String val){this.text = StringUtil.truncate(val,size);}

[update] because you can't really update the database, I will recommend an aspect to intercept string setters and check their length. It may look like this (the syntax may be closed, but I didn't test this)

private static final MAX_SIZE_OF_STRINGS = 255;

@Around("execution(* your.package.*.set*(..)) && args(java.lang.String)")
public void checkAroundSetter(final ProceedingJoinPoint pjp)
    throws Throwable {
    Object[] args = pjp.getArgs();
    for (int i = 0; i < args.length; i++) {
        if (args[i] instanceof String && ((String) args[i]).size() > MAX_SIZE_OF_STRINGS) {
            args[i] = ((String)args[i]).subString(0,MAX_SIZE_OF_STRINGS) ;
        }
    }
    pjp.proceed(args);
}

Moreover, if a layer has to check that the defined column size matches all the data in each inserted table, there will be additional overhead

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>