Hi,

I am using Deltaspike 1.9.3 in Wildfly 14.

I have a CDI bean with a method that is supposed to insert or update an entity, 
like this:

@Named
@ApplicationScoped
public class StuffService {

    @Inject
    private StuffRepository repository; // StuffRepository extends 
EntityRepository<Stuff, Long>

...

    @Transactional
    public void save(Stuff stuff) throws Exception {

        if (stuff.getCode() == null) {
            repository.save(stuff);

        } else {

            Stuff entity = getByCode(stuff.getCode()); // code is @Id
            entity.setName(stuff.getName());
            repository.save(entity);
        }
    }

This works, but looking at the EntityRepository.save javadoc, I understand that 
it already does what I want, decide if to update or insert a new record based 
on the presence/absence of a primary key value.

However, if I call repository.save() on an existing entity (so I remove the if 
and always go in the first branch), I get an exception:

javax.persistence.TransactionRequiredException: WFLYJPA0060: Transaction is 
required to perform this operation (either use a transaction or extended 
persistence context)
    at 
org.jboss.as.jpa@14.0.1.Final//org.jboss.as.jpa.container.AbstractEntityManager.transactionIsRequired(AbstractEntityManager.java:877)
    at 
org.jboss.as.jpa@14.0.1.Final//org.jboss.as.jpa.container.AbstractEntityManager.merge(AbstractEntityManager.java:564)

What happens here? How come a transaction does not exist unless I create a new 
object and transfer the data into it?

What I guess might be relevant is that the Stuff entity comes from a ViewScoped 
bean, from a previous request.

Note, I am using container-managed transactions, and 
javax.transaction.Transactional. Should I use 
org.apache.deltaspike.jpa.api.transaction.Transactional? What is the difference?

Thanks in advance,

Lucian



Reply via email to