对于这个JAX-RS应用程序,我使用Grizzly而不是Glassfish。我是这项技术的新手,所以我一直在谷歌上搜索,似乎找不到如何在应用程序中设置Service/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;
}
}
道
@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;
}
}