Schnappi
Schnappi

Reputation: 125

Getting javax.persistence.TransactionRequiredException on JPA + JAX-RS

I'm having a troubles with my JavaEE application. I'm running Hibernate + Jersey on TomEE.

This is my base class:

public abstract class BaseEntityManager<E, K>{
protected Class entityClass;

@PersistenceContext
protected EntityManager em;

public BaseEntityManager() {
    ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[0];
}

public EntityManager getManager() {
    return em;
}

public void persist(E entity) { em.persist(entity); }

public void remove(E entity) { em.remove(entity); }

public E findById(K primaryKey) { return (E)em.find(entityClass, primaryKey); }


}

And this is the class for concrete type:

@Stateless
public class SomethingManager extends BaseEntityManager<SomethingEntity, Integer>{}

And here is my resource. I deserialize data from JSON in my JSONCreator. There are some IDs of referenced entities. Then in the method "new" I try to persist new object which works fine, however I cannot merge the relation from the other entities back to the new object (the IDs of referenced entities I mentioned earlier).

@Path("/Something")
public class Something{

// Other entity managers here ....
@EJB
SomethingManager smm;

@EJB
OtherManager ttem;


@Secured
@POST
@Path("/new")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public SomethingEntity add(@Context HttpServletRequest req, SomethingEntity r)
{
   ...


    try {


        for (int i = 0; i < r.getOtherEntities().size(); i++) {
            OtherEntity x = (r.getOtherEntities().get(i));
            x = ttem.findById(x.getId());
            x.getSomethingEntities().add(r);
            ttem.getManager().merge(x);
        }
    }
    catch (Exception e)
    {
        e.printStackTrace(); // TODO Intelligent logging
        return null;
    }

    return r;
    }
}

This throws the exception ttem.getManager().merge(x);

What seems to be an issue?

Thank you.

Upvotes: 0

Views: 1626

Answers (1)

Rouliboy
Rouliboy

Reputation: 1377

There is no active transaction when calling your Rest resource. I can see 2 solutions :

  1. Add the @Transactional interceptor binding annotation to your add method of Something class if your server is Java EE 7 compliant.
  2. Annotate your Something class with @Stateless annotation. You will then have EJB transaction managed by container.

Upvotes: 2

Related Questions