Я использую в своем приложении web-сервис jax-rs restful с локаторами подресурсов. Однако после передачи entityManager на подресурс я не могу сохранить какие-либо новые объекты в этом подресурсе.
EntityManager позволяет мне запрашивать данные.
Это мой основной ресурс:
@Path("/registrations")
@Stateless
public class RegistrationsResource {
@Context
private UriInfo context;
@PersistenceContext(unitName="pctx")
private EntityManager em;
public RegistrationsResource() {
}
//POST method ommited
@Path("{regKey}")
public RegistrationResource getRegistrationResource(@PathParam("regKey")
String regKey) {
return RegistrationResource.getInstance(regKey, em);
}
}
А это мой подресурс:
public class RegistrationResource {
private String regKey;
private EntityManager em;
private RegistrationResource(String regKey, EntityManager em) {
this.regKey = regKey;
this.em = em;
}
@Path("securityQuestion")
@GET
public String getQuestion() {
return "iamahuman"+regKey;
}
@Path("securityQuestion")
@POST
public void postSecurityAnswer(String answer) {
if(!answer.equals("iamahuman"+regKey)){
throw new WebApplicationException(Status.BAD_REQUEST);
}
//Getting this information works properly
List<RegistrationEntity> result = em.createNamedQuery("getRegistrationByKey")
.setParameter("regKey", regKey).getResultList();
switch(result.size()){
case 0 :
throw new WebApplicationException(Status.NOT_FOUND);
case 1:
break;
default:
throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
}
RegistrationEntity reg = result.get(0);
UserEntity newUser = new UserEntity();
newUser.setHashedPassword(reg.getPwHash(), reg.getSalt());
newUser.setUsername(reg.getUsername());
newUser.setName(reg.getName());
newUser.setSurname(reg.getSurname());
//CRASHES HERE
em.persist(newUser);
}
}
Как видите, он берет объект регистрации из базы данных, создает нового пользователя для регистрации и пытается сохранить его. Однако em.persist (newUser) создает исключение TransactionRequiredException.
У меня вопрос: как передать EntityManager на подресурс, чтобы он мог правильно сохранять новые объекты?