【发布时间】:2018-01-21 07:03:24
【问题描述】:
我正在开发一个简单的问答服务 (Jersey JAX-RS)。通过这项服务,到目前为止,我已经提出了以下资源(可能会增加)。
- GET|POST -------------/问题
- GET|PUT|DELETE -- /questions/{id}
- GET|POST ------------ /questions/{id}/answers
- GET|PUT|DELETE - /questions/{questionId}/answers/{answerId}
这是我的资源类,可满足上述所有路径。
@Path("/questions")
public class QuestionResource {
@Inject
private QuestionService questionService;
@GET
...<list of questions>
@POST
...<a new question>
@Path("{id}")
...<a question>
@PUT
@Path("{id}")
...<update a question>
@DELETE
@Path("{id}")
...<delete a question>
@GET
@Path("{id}/answers")
...<list of answers>
@POST
@Path("{id}/answers")
...<a new answer for a question>
@GET
@Path("{questionId}/answers/{answerId}")
...<an answer for a question>
@PUT
@Path("{questionId}/answers/{answerId}")
...<update an answer for a question>
@DELETE
@Path("{questionId}/answers/{answerId}")
...<delete an answer for a question>
}
这有相应的服务和持久层 - QuestionService/QuestionServiceImpl 和 QuestionRepository/QuestionRepositoryImpl。但是,对于我应该放置哪个服务和存储库来处理最后五个请求的方法,我有点困惑。我应该把它们都放到问题服务和存储库还是另一个类 - 回答服务和存储库?
由于答案和问题的多对一关系,我正在考虑后者(JPQL NamedQuery - SELECT a FROM Answer a WHERE a.question.id = :questionId)。这意味着我的 QuestionResource 中除了 QuestionService 之外,我还会有 AnswerService。可以吗。
请赐教。谢谢。
【问题讨论】:
-
我认为你应该把你的方法放在主资源中,比如如果你想要一个特定问题的答案,那么你的主要资源就是问题,你应该把方法放在问题类中等等。
-
感谢您的快速回答。你介意解释一下原因吗?
-
我认为我不应该包含这个“由于答案和问题的多对一关系,我正在考虑后者(JPQL NamedQuery - SELECT a FROM Answer a WHERE a.question. id = :questionId)。”我的问题。看起来无关紧要。
-
是的,这无关紧要,在 RESTful API 中,一切都是资源,当涉及到关系时,您会考虑主要资源和其他资源。在您的情况下,答案可以是没有问题的主要资源,或者换句话说,您的一个资源依赖于另一个资源。您的答案绝对取决于问题。
-
我明白了。谢谢你。请发表您的问题,如果没有其他合理的答案,我会接受。
标签: java rest jersey service-layer data-layer