0

I am trying to build an application with JAX-RS and JPA persistency ; for now, I am able to persist objects directly from the resource class, but I would like to use another layer between REST and the database.

What I would like to do, is to inject the EntityManager to my UserService, and then call my UserService from the resource..

Here is what I've done, but I always have a NullPointerException on the userService attribute... Any idea ?

UserResource

@Path( "/user" )
@Produces( MediaType.APPLICATION_JSON )
public class UserResource {

    @EJB
    private UserService userService;

    @GET
    public User findAll() {
        // TEST
        User user = userService.create( "testLogin", "testPassword", "user" );

        return user;
    }

}

UserService

public class UserService {

    @Inject
    private EntityManager em;

    /**
     * Create a new user
     * 
     * @param user New user or null if error
     */
    public User create( String login, String password, String type ) {
        User user = null;

        try {
            AuthenticationService authService = new AuthenticationService();
            byte[] salt = authService.generateSalt();
            byte[] encryptedPassword = authService.getEncryptedPassword( password, salt );

            user = new User();
            user.setLogin( login );
            user.setSalt( salt );
            user.setPassword( encryptedPassword );
            user.setType( type );

            em.persist( user );
        } catch( NoSuchAlgorithmException e ) {
            System.out.println( "Error during encryption" );
            e.printStackTrace();
        } catch( DAOException e ) {
            System.out.println( "Error accessing database" );
            e.printStackTrace();
        } catch( Exception e ) {
            e.printStackTrace();
        }

        return user;
    }

}

Resources

public class Resources {

    @Produces
    @PersistenceContext( unitName="configurator_db" )
    private EntityManager em;

}
Jérémy Dutheil
  • 6,099
  • 7
  • 37
  • 52

1 Answers1

0

The @EJB annotation is not valid in the Jax-RS specification: it may be used in the EJB layer. This is why nothing is injected in the userService. If you want to get a UserService instance, you must:

  1. either use a JNDI lookup of form java:global[/<app-name>]/<module-name>/<bean-name>
  2. Annotate your Rest Resource with @Stateless as it is described here (example 2).
Community
  • 1
  • 1
V G
  • 18,822
  • 6
  • 51
  • 89