0
我爲此JAX-RS應用程序使用Grizzly而不是Glassfish。我對這項技術很陌生,所以我一直在搜索Google,並且似乎無法找到如何在我的應用中設置服務/ DAO層的好輪廓。如何使用Grizzly/JAX-RS創建DAO /服務層
下面是我的工作原型。
我的資源
@Path("/helloworld")
@Stateless
public class MyResource {
@EJB //DOESN'T WORK - how do I map this service to this resource?
WorkflowService workflowService;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String TestRequest() {
Workflow workflow = new Workflow();
workflow.setName("test");
workflowService.save(workflow);
return "Workflow ID:";
}
}
吾道
public class WorkflowDao {
@PersistenceContext(unitName = "unit")
private EntityManager entityManager;
public int save(Workflow workflow) {
entityManager.persist(workflow);
return workflow.getId();
}
}
我的服務
@Stateless
public class WorkflowService {
@EJB //I know EJB is probably wrong here, not sure what else to do yet.
WorkflowDao workflowDao;
public int save(Workflow workflow) {
int id = workflowDao.save(workflow);
return id;
}
}
更新 - 我意識到EJB不能用於我的設置。所以我的問題是,什麼?如何使我的資源可訪問服務?
--------------決賽/工作守則--------------
資源
@Path("/helloworld")
public class MyResource {
WorkflowService workflowService;
public MyResource() {
workflowService = new WorkflowService();
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public String TestRequest() {
Workflow workflow = new Workflow();
workflow.setName("test");
workflowService.save(workflow);
return "Workflow ID:";
}
}
服務
public class WorkflowService {
WorkflowDao workflowDao;
public WorkflowService() {
workflowDao = new WorkflowDao();
}
public int save(Workflow workflow) {
int id = workflowDao.save(workflow);
return id;
}
}
DAO
@Singleton
public class WorkflowDao {
private EntityManager entityManager;
public int save(Workflow workflow) {
getEntityManager().persist(workflow);
return workflow.getId();
}
protected EntityManager getEntityManager() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("unit");
EntityManager em = emf.createEntityManager();
return em;
}
}
謝謝 - 我更新了我的問題 – Webnet 2013-02-14 15:03:19
要回答您更新的問題,我在之前的回答中添加了Spring。 另外,您可以選擇在您的JAXRS實現中實例化您的服務,並使您的DAO成爲單例。 – 2013-02-14 15:08:49
當它們在我的JAXRS實現中實例化時,是否可以提供代碼示例?例如,我知道我可以執行'workflowservice = new WorkflowService();',但是如何將'EntityManager'映射到DAO?我將添加'@ Singleton'到我的DAO – Webnet 2013-02-14 15:13:32