Skip to content

Selecting a value of a different type with a transformer

gert-wijns edited this page Sep 13, 2014 · 2 revisions

When the type on the dto doesn't match the type on the entity property, provide a SelectionValueTransformer to transform the result prior to setting it on the dto.

// example: some date was saved in a String value
Product product = query.from(Product.class);

ProductDetailsDto dto = query.select(ProductDetailsDto.class);
dto.setId(product.getId());

// property1 is a String property, which can be transformed to a date:
dto.setValidUntilDate(query.select(Date.class, 
        product.getManyProperties().getProperty1(),
        new SelectionValueTransformer<String, Date>() {
    @Override
    public Date convert(String a) {
        try {
            return DateFormat.getDateInstance().parse(a);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}));

=> "select hobj1.id as id, 
           hobj1.manyProperties.property1 as validUntilDate 
    from Product hobj1"
Clone this wiki locally