For a general approach, when you do not need to specify one PropertyEditor for each object, you can use 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; } }
Aleksander BlomskΓΈld
source share