对于不需要为每个实体指定一个 PropertyEditor 的通用方法,您可以使用 ConditionalGenericConverter:
public final class GenericIdToEntityConverter implements ConditionalGenericConverter {
private static final Logger log = LoggerFactory.getLogger(GenericIdToEntityConverter.class);
private final ConversionService conversionService;
@PersistenceContext
private EntityManager entityManager;
@Autowired
public GenericIdToEntityConverter(ConversionService conversionService) {
this.conversionService = conversionService;
}
public Set<ConvertiblePair> getConvertibleTypes() {
return ImmutableSet.of(new ConvertiblePair(Number.class, AbstractEntity.class),
new ConvertiblePair(CharSequence.class, AbstractEntity.class));
}
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return AbstractEntity.class.isAssignableFrom(targetType.getType())
&& this.conversionService.canConvert(sourceType, TypeDescriptor.valueOf(Long.class));
}
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
Long id = (Long) this.conversionService.convert(source, sourceType, TypeDescriptor.valueOf(Long.class));
Object entity = entityManager.find(targetType.getType(), id);
if (entity == null) {
log.info("Did not find an entity with id {} of type {}", id, targetType.getType());
return null;
}
return entity;
}
}