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;
}