或者,您可以使用生命周期注释:
@Entitypublic class MyEntity { @PostLoad protected void repair(){ if(myStringProperty!=null)myStringProperty=myStringProperty.trim(); } private String myStringProperty; public String getMyStringProperty() { return myStringProperty; } public void setMyStringProperty(String myStringProperty) { this.myStringProperty = myStringProperty; }}
如果在多个实体上发生这种情况,则可以创建一个自定义批注并编写一个专用的EntityListener。
注解
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface Trim {}
听众
public class TrimListener { private final Map<Class<?>, Set<Field>> trimProperties = new HashMap<Class<?>, Set<Field>>(); @PostLoad public void repairAfterLoad(final Object entity) throws Exception { for (final Field fieldToTrim : getTrimProperties(entity.getClass())) { final String propertyValue = (String) fieldToTrim.get(entity); if (propertyValue != null) fieldToTrim.set(entity, propertyValue.trim()); } } private Set<Field> getTrimProperties(Class<?> entityClass) throws Exception { if (Object.class.equals(entityClass)) return Collections.emptySet(); Set<Field> propertiesToTrim = trimProperties.get(entityClass); if (propertiesToTrim == null) { propertiesToTrim = new HashSet<Field>(); for (final Field field : entityClass.getDeclaredFields()) { if (field.getType().equals(String.class) && field.getAnnotation(Trim.class) != null) { field.setAccessible(true); propertiesToTrim.add(field); } } trimProperties.put(entityClass, propertiesToTrim); } return propertiesToTrim; }}
现在使用注释所有相关的String字段,
@Trim并在persistence.xml中将侦听器注册为默认实体侦听器:
<persistence-unit ..> <!-- ... --> <default-entity-listeners> com.somepackage.TrimListener and.maybe.SomeOtherListener </default-entity-listeners></persistence-unit>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)