Search code examples
quarkusquarkus-panache

PanacheRepositoryResource - Transaction is not active


I'm using Quarkus with Hibernate Rest Data Panache and I'm having issues while persisting data with a custom endpoint.

import io.quarkus.hibernate.orm.rest.data.panache.PanacheRepositoryResource;
import io.quarkus.rest.data.panache.ResourceProperties;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;

@ResourceProperties
public interface EntityResource extends PanacheRepositoryResource<EntityRepository, Entity, Long> {

        @POST
        @Path("/foo")
        @Transactional
        default Entity fooMethod(Entity entityToPersist) {
            CDI.current().select(EntityRepository.class).get().persist(entityToPersist);

            return entityToPersist;

        }

    }

Is throwing

Transaction is not active, consider adding @Transactional to your method to automatically activate one.

Any suggestion? As alternative I have though to call the base "POST", but I have not found a way to do it.


Solution

  • Unfortunately, the annotation @Transactional does not work for interfaces, so you need to use the programmatic approach:

    @ResourceProperties
    public interface EntityResource extends PanacheRepositoryResource<EntityRepository, Entity, Long> {
    
            @POST
            @Path("/foo")
            @Transactional
            default Entity fooMethod(Entity entityToPersist) {
    
                QuarkusTransaction.requiringNew().run(() -> {
                      entityToPersist.persist();
                });
    
                return entityToPersist;
            }
    
    }
    

    You can find more information about the programmatic approach here: https://quarkus.io/guides/transaction#programmatic-approach

    By the way, the very same limitation was found when using REST Data with Panache and Reactive and was fixed by https://github.com/quarkusio/quarkus/pull/34542 (will be part of Quarkus 3.3). I will see if we can implement the same fix in REST Data with Panache and ORM.

    I hope it helps!