Equivalent of Spring's BeanUtils.copyProperties(source, dest, notCopiedAttrNames[]) in Quarkus? How to easily copy a bean's attributes onto another?

35 views Asked by At

I'm new to Quarkus, exploring it to build a competence coming from Spring. There, I would very often use something like:

BeanUtils.copyProperties(inputBean, beanToUpdate, new String[]{"attrName1", "attrName1"});

(BeanUtiles being a class included in the standard spring-beans artifact).

This is very common in Update (CRUD) methods where you receive an input bean with updated attributes and you've to pour them onto an entity you retrieve from the DB and then persist the latter. The third param is very useful, allowing to list a set of attribute names that you don't want to copy (coupled with some custom code it can be used to avoid null input attributes). It'd be very useful in Quarkus as well in order to avoid pouring the ID attribute, thus triggering the duplicate key exception.

I've been unable to find anything similar in Quarkus. The code I've seen so far show explicit setter invoked attribute-by-attribute. That seems unpractical for many entities and for maintenance when you add new attributes over time.

Any hint?


This is a bare-bone implementation of the Update method I'm trying to experiment with:

    @PUT
    @Path("/{id}")
    @Transactional
    public MyEntity update(@PathParam("id") Long id, MyEntity inputBean) {
        MyEntity entity = myEntityRepository.findById(id); // Repo implements PanacheRepository
        if(null == entity) {
            throw new NotFoundException();
        }

        // map all fields from the inputBean onto the existing entity
        entity.setAttribute1(inputBean.getAttribute1());  // This is OK
        entity.setAttribute2(inputBean.getAttribute2());  // This is OK
        // BeanUtils.copyProperties(entity, inputBean);   // This is NOK as it copies also inputBean.id, triggering the duplicate key exception
        persistAndFlush(entity);
        return entity;
    }
0

There are 0 answers