2015-04-20 44 views
1

我正在使用JPA。如果長度超過列大小,我需要在保存前修剪字符串。我有下面的代碼。截斷要保存的字符串?

人們可以根據在二傳手的JPA註解相應字段截斷的字符串:

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; 

現在的問題是,我想上述許多實體的許多領域的邏輯。我如何編寫/使上面的邏輯是通用的,以避免在所有字段的所有實體中重複代碼。

+2

您可以創建自己的註釋來完成這項工作。 –

+0

@LuiggiMendoza是否存在帶* active *代碼的註釋?我誤解你的評論嗎? – laune

+0

@laune你的意思是帶有*活動代碼的註釋*? –

回答

0

我看到了兩個選擇,這兩個選項都不會像你想要的那樣無人問津。

  1. 在庫org.Reflections中使用某個方面。我認爲這必須是使用aspectj進行編譯的時間,因爲您必須使用Reflections來獲取所有包含註釋的字段,然後確定哪些setter屬於這些字段,然後應用這些字段。
  2. 有一個靜態方法,它在每個setter中使用內部反射和一行代碼。

我試過第一個路徑,它開始變得太複雜了,所以我嘗試了#2並使用了在this question中發現的東西。

public static String truncate(String string) 
{ 
    try 
    { 
     final StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[2]; 
     final Class<?> clazz = Class.forName(stackTraceElement.getClassName()); 
     final BeanInfo beanInfo = Introspector.getBeanInfo(clazz); 
     final String methodName = stackTraceElement.getMethodName(); 
     final PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); 
     for(final PropertyDescriptor descriptor : props) 
     { 
      if(descriptor.getWriteMethod() != null) 
      { 
       if(methodName.equals(descriptor.getWriteMethod().getName())) 
       { 
        System.out.println(descriptor.getDisplayName()); 
        final Column annotation = 
          clazz.getDeclaredField(descriptor.getDisplayName()).getAnnotation(Column.class); 
        if(annotation != null) 
        { 
         final int size = annotation.length(); 
         if(size == 255) 
         { 
          // Highly likely we hit the default value, which means nothing was specified so just 
          // move along 
         } 
         else if(string.length() > size) 
         { 
          string = string.substring(0, size); 
         } 
        } 

        break; 
       } 
      } 
     } 
    } 
    catch(final IntrospectionException e) 
    { 
    } 
    catch(final Exception e) 
    { 
    } 

    return string; 
} 

你在二傳手

public void setPersonTitle(final String personTitle) 
{ 
    this.personTitle = JpaStringTruncator.truncate(personTitle); 
} 

這假定您的設置器調用靜態方法,所以你只需要原路返回幾個元素有一個基本的列定義

@Column(name = "personTitle", length = 5) 
private String personTitle; 

然後在StackTrace中。