0

I have an entity where I set the max for every String field like the following:

@Column(name = "abc")
@Size(max = 10)
private String abc;

@Column(name = "xyz")
@Size(max = 50)
private String xyz;

I want to write a Converter to truncate that field if exceeds max size. Something like this:

import javax.persistence.AttributeConverter;
import javax.persistence.Convert;

@Convert
public class TruncatedStringConverter implements AttributeConverter<String, String> {
  private static final int LIMIT = 999;

  @Override
  public String convertToDatabaseColumn(String attribute) {
    if (attribute == null) {
      return null;
    } else if (attribute.length() > LIMIT) {
      return attribute.substring(0, LIMIT);
    } else {
      return attribute;
    }
  }

  @Override
  public String convertToEntityAttribute(String dbData) {
    return dbData;
  }
}

But the thing is that I can't use LIMIT since I need to look to the Size annotation. Is there any way to access the field name from the converter?

This way I could use reflection to read the max size.

Thank you!

briba
  • 2,857
  • 2
  • 31
  • 59
  • Maybe this one helps you: https://stackoverflow.com/questions/4296910/is-it-possible-to-read-the-value-of-a-annotation-in-java – Ralf Renz May 04 '22 at 09:28
  • thanks @RalfRenz! I can read field name from field.getName() using getDeclaredFields but I'm wondering if there's a way to access inside the converter. I only know the value inside the converter but I am not sure from which variable it belongs :) – briba May 04 '22 at 10:08
  • There is a much easier solution to this: Move the `@Column` and `@Size` annotations to the get-method of each property. For example, `@Size(max = LIMIT) public String getXyz() { return xyz; }`. Then the corresponding set-method can take care of truncation. – VGR May 04 '22 at 12:02
  • That's also a possibility! Or maybe I will just write one method to go over the entire entity object after it gets filled out/ Thanks @VGR! – briba May 04 '22 at 12:19

0 Answers0