user1079877
user1079877

Reputation: 9358

Use @RequestScoped and @Produces to Inject User Entity into the Jersey handler

User Entity class:

@Entity
public class User implements Serializable {

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    public List<Site> sites;

Facade class to access database:

@Stateless
public class UserFacade extends AbstractFacade<User, Long> {

    @PersistenceContext
    private EntityManager em;

    ...
}

Resource class for User injection:

@RequestScoped
public class Resource {

    @Inject
    UserFacade userFacade;

    @Inject
    HttpServletRequest request;

    @Produces
    public User getUser() {
        final String name = request.getUserPrincipal().getName();
        // ... find user in database ...
    }

}

And Jersey handler:

@Stateless
@Path("/sites")
public class Sites {    

    @EJB
    SiteFacade siteFacade;

    @Inject
    User user;

    ...

Here is the problem now:

When I want to access user.sites list, I'm getting lazy load exception. But apparently because User injected by RequestScoped provider, it should refresh per request with same EntityManager session. Right?

Is there anyway I inject User Entity per rest request into Rest handler class?

Upvotes: 0

Views: 899

Answers (1)

Harald Wellmann
Harald Wellmann

Reputation: 12855

The EntityManager is bound to the transaction, not to the request scope.

So the User producer method and your Sites business method are called in two distinct transactions, which explains the LazyLoadException.

Upvotes: 1

Related Questions