我在我的應用程序中使用子資源定位器使用jax-rs restful web服務。但是,在將entityManager傳遞給子資源後,我無法在此子資源中保留任何新對象。如何用jax-rs子資源定位器處理持久化上下文(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傳遞給子資源,以便它可以正確保留新對象?
看到http://stackoverflow.com/questions/7456755/jersey-rest-sub-resource-cdi – 2013-08-11 15:38:49